问:
How can I obtain the keypress european "è" char using Java robot class
I'm writing a virtual keyboard for my application and I'm using Java robot in order to simulate the keypress event of each keyboard button.
Everything is right except that I can't find the keycode for European special chars, specifically the italian ones.
Scanning every possible code I've found that:

```<code>à is KeyEvent.VK_DEAD_ABOVERING
ì is KeyEvent.VK_DEAD_CIRCUMFLEX
ò is KeyEvent.VK_DEAD_CEDILLA
ù is KeyEvent.VK_DEAD_GRAVE
</code>```

but I'm missing the keycode for "è", it appears like if no code can produce this char.

I've also already tried to get the missing code using tools that prints out each key pressed on the phisical keyboard, but I get "unkown" for each one of the above chars (including the "è").

Here is a piece of code to test it

```<code>package robottest;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class RobotTest {

    private static Robot robot;

    public static void main(String[] args) {
        // TODO code application logic here
        try {
            robot = new Robot();
            int keyCode = KeyEvent.VK_DEAD_CARON;
            robot.keyPress(keyCode);
            robot.keyRelease(keyCode);

        } catch (AWTException ex) {
            System.out.println("Exception"+ex);
        }
    }
}
</code>```

It is minimal, you can compile it and run with

```<code>java -jar RobotTest.jar
</code>```

Here is what i get modifying my source to act as a kind "code scanner" ...

```<code>package robottest;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import javafx.scene.input.KeyCode;

public class RobotTest {

    private static Robot robot;

    public static void main(String[] args) {
        // TODO code application logic here
        try {
            robot = new Robot();
/*            int keyCode = KeyEvent.VK_DEAD_BREVE;
            robot.keyPress(keyCode);
            robot.keyRelease(keyCode);
*/
            for (int keyCode = KeyEvent.VK_DEAD_GRAVE; keyCode <KeyEvent.VK_DEAD_GRAVE+20; keyCode++) {
                System.out.print("Code "+keyCode+" ");
                robot.keyPress(keyCode);
                robot.keyRelease(keyCode);
                System.out.println("");
            }

        } catch (AWTException ex) {
            System.out.println("Exception"+ex);
        }
    }
}
</code>```

The output is:

```<code>Code 128 ù
Code 129 ,
Code 130 ì
Code 131 3
Code 132 -
Code 133 ù
Code 134
Code 135 .
Code 136 à
Code 137 2
Code 138
Code 139 ò
Code 140 0
Code 141
Code 142
Code 143
Code 144
Code 145
Code 146
Code 147
</code>```

答:
The value you are looking for is VK_DEAD_CARON, code 138

You can find any value associated to a character starting from ASCII table: search for its numeric value, and then you will find the associated variable in java KeyEvent

Another possibility is to implement a custom keyboard

Body:
I'm writing a virtual keyboard for my application and I'm using Java robot in order to simulate the keypress event of each keyboard button.
Everything is right except that I can't find the keycode for European special chars, specifically the italian ones.
Scanning every possible code I've found that:

à is KeyEvent.VK_DEAD_ABOVERING
ì is KeyEvent.VK_DEAD_CIRCUMFLEX
ò is KeyEvent.VK_DEAD_CEDILLA
ù is KeyEvent.VK_DEAD_GRAVE

but I'm missing the keycode for "è", it appears like if no code can produce this char.

I've also already tried to get the missing code using tools that prints out each key pressed on the phisical keyboard, but I get "unkown" for each one of the above chars (including the "è").

Here is a piece of code to test it

package robottest;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class RobotTest {

    private static Robot robot;

    public static void main(String[] args) {
        // TODO code application logic here
        try {
            robot = new Robot();
            int keyCode = KeyEvent.VK_DEAD_CARON;
            robot.keyPress(keyCode);
            robot.keyRelease(keyCode);

        } catch (AWTException ex) {
            System.out.println("Exception"+ex);
        }
    }
}

It is minimal, you can compile it and run with

java -jar RobotTest.jar

Here is what i get modifying my source to act as a kind "code scanner" ...

package robottest;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import javafx.scene.input.KeyCode;

public class RobotTest {

    private static Robot robot;

    public static void main(String[] args) {
        // TODO code application logic here
        try {
            robot = new Robot();
/*            int keyCode = KeyEvent.VK_DEAD_BREVE;
            robot.keyPress(keyCode);
            robot.keyRelease(keyCode);
*/
            for (int keyCode = KeyEvent.VK_DEAD_GRAVE; keyCode <KeyEvent.VK_DEAD_GRAVE+20; keyCode++) {
                System.out.print("Code "+keyCode+" ");
                robot.keyPress(keyCode);
                robot.keyRelease(keyCode);
                System.out.println("");
            }

        } catch (AWTException ex) {
            System.out.println("Exception"+ex);
        }
    }
}

The output is:

Code 128 ù
Code 129 ,
Code 130 ì
Code 131 3
Code 132 -
Code 133 ù
Code 134
Code 135 .
Code 136 à
Code 137 2
Code 138
Code 139 ò
Code 140 0
Code 141
Code 142
Code 143
Code 144
Code 145
Code 146
Code 147


来源: stackexchange

问:
JUnit Annotations not being run through
I have a JUnit Framework with the following annotations @before, @test, @After.

However when I run through my tests the @After Annotation is never initialised and therefore the browser doesn't close.

I've run my tests using JUnit and they all pass but the tear down step never works.

I decided to try see if any of the annotations worked, so I removed the @before and @test and the test still run and passed which suggests to me that they are not being used at all.

This is my Selenium set up:

```<code>public SeleniumSetup() {

    }

    @Before
    public void prepareBrowserForSelenium() throws Exception {
//      setup();
        if(DriverSingleton.getDriver() == null)
        {
            setup();
        }
        else
        {
            driver = DriverSingleton.getDriver();
        }

    }

    public void setup() throws Exception {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\antho\\Automation\\WebAutomation\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.ultimateqa.com");
        driver.manage().window().maximize();
        DuringTest();
    }

    @Test
    public void DuringTest() throws Exception{
        System.out.println("test has started");
        assertEquals(true, driver.getPageSource().contains("Learn Critical Automation and Dev Skills"));

        System.out.println("Learn Critical Automation and Dev Skills copy has been verified");

        driver.findElement(By.linkText("Automation Exercises")).click();

        assertEquals(true, driver.getPageSource().contains("Automation Practice"));
        System.out.println("Automation Practice copy has been verified");

        driver.findElement(By.linkText("Big page with many elements")).click();
    }

    @After
    public static void tearDown() throws Exception {
        driver.close();
    }
</code>```

This is my DriverSingleton;

```<code>    private static WebDriver driver;

    public DriverSingleton () {

    }

    public static WebDriver getDriver() {
        return driver;
    }

    public static void setDriver (WebDriver driver) {
        DriverSingleton.driver = driver;
    }

}
</code>```

After my tests have run I expect the browser to close down.

I have added DuringTest(); to my @Before class, which I suspect is the only reason the @Test class is getting called, without that this the @Test doesn't work.

答:
First you shall not invoke @Test inside your setup method by calling DuringTest(). JUnit framework would take care of Test Method by looking @Test annotations. So you do not need to call it explicitly.

Make both @Before & @After method as non static.

ContentLicense: CC BY-SA 4.0

Title: JUnit Annotations not being run through

Body:
I have a JUnit Framework with the following annotations @before, @test, @After.

However when I run through my tests the @After Annotation is never initialised and therefore the browser doesn't close.

I've run my tests using JUnit and they all pass but the tear down step never works.

I decided to try see if any of the annotations worked, so I removed the @before and @test and the test still run and passed which suggests to me that they are not being used at all.

This is my Selenium set up:

public SeleniumSetup() {

    }

    @Before
    public void prepareBrowserForSelenium() throws Exception {
//      setup();
        if(DriverSingleton.getDriver() == null)
        {
            setup();
        }
        else
        {
            driver = DriverSingleton.getDriver();
        }

    }

    public void setup() throws Exception {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\antho\\Automation\\WebAutomation\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.ultimateqa.com");
        driver.manage().window().maximize();
        DuringTest();
    }

    @Test
    public void DuringTest() throws Exception{
        System.out.println("test has started");
        assertEquals(true, driver.getPageSource().contains("Learn Critical Automation and Dev Skills"));

        System.out.println("Learn Critical Automation and Dev Skills copy has been verified");

        driver.findElement(By.linkText("Automation Exercises")).click();

        assertEquals(true, driver.getPageSource().contains("Automation Practice"));
        System.out.println("Automation Practice copy has been verified");

        driver.findElement(By.linkText("Big page with many elements")).click();
    }

    @After
    public static void tearDown() throws Exception {
        driver.close();
    }

This is my DriverSingleton;

    private static WebDriver driver;

    public DriverSingleton () {

    }

    public static WebDriver getDriver() {
        return driver;
    }

    public static void setDriver (WebDriver driver) {
        DriverSingleton.driver = driver;
    }

}

After my tests have run I expect the browser to close down.

I have added DuringTest(); to my @Before class, which I suspect is the only reason the @Test class is getting called, without that this the @Test doesn't work.


问:
xcodebuild failure clang:error no such file or directory:
Having a problem when building with xcodebuild. My project/app builds fine with the Xcode - gui. It simply isn't finding/building the libcryptopp library which is part of the build process.

The error is:

```<code>clang: error: no such file or directory: '/Users/builder/repo/ioskpay/xcode-cryptopp/cryptopp/build/Release-iphoneos/libcryptopp.a'
</code>```

This particular file should be derived from another project inside the main app - xcodebuild simply isn't correctly pointing at the right file folder which should be:

```<code>~/Library/Developer/Xcode/DerivedData
</code>```

Any ideas?

答:
My xCode info is:

I faced similar errors during xcode building projects (native swift, flutter, react native, native script) in which I got error messages related to clang compilar. Errors like:

clang-4.0: error: no such file or directory: '/Users/xxxxxxxx/Library/Developer/Xcode/DerivedData/xxxxxxxxxxxxxxx/Index/Data Store'

clang-4.0: error: cannot specify -o when generating multiple output files

others

Despite of errors related with DerivedData for native apps can be fixed by deleting the directory and, eventually, restart xCode and even restart the machine... in this case, you will see that after deleting the directory and start building process again, the error comes back.

Then, is the moment of checking the clang installation by running clang --version. The normal output will be something like:

as you can see the InstalledDir is incorrect for xCode. In my case, some days ago I needed to install Anaconda app (R, Python, etc) and, now, I remember that I had to install some dependencies and one of them was clang and its installation was altered.
To fix this problem (in my case that I will not need anaconda any more): (edited)

1.- Delete anaconda and all its dependencies (I recommend to use App Cleaner).
  2.- Re-install xCode

After reinstalling xCode, if you type again clang --version, you'll get this:

More info at: https://github.com/flutter/flutter/issues/32457#issuecomment-496161092

Hopefully, this info helps some else.

Best

ContentLicense: CC BY-SA 3.0

Body:
Having a problem when building with xcodebuild. My project/app builds fine with the Xcode - gui. It simply isn't finding/building the libcryptopp library which is part of the build process.

The error is:

clang: error: no such file or directory: '/Users/builder/repo/ioskpay/xcode-cryptopp/cryptopp/build/Release-iphoneos/libcryptopp.a'

This particular file should be derived from another project inside the main app - xcodebuild simply isn't correctly pointing at the right file folder which should be:

~/Library/Developer/Xcode/DerivedData

Any ideas?


问:
What exactly happens when awaiting a promise in JavaScript?
One point that I can’t seem to find anywhere in documentation or related resources is what the procedure is, in regards to the calling function and the event loop, when JS hits the await keyword.

Here’s what the specs state:

The await expression causes async function execution to pause until a Promise is resolved, that is fulfilled or rejected, and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise.

That all makes sense, but what really is meant by pause? Does the function immediately return to the caller and then when the promise that’s being awaited resolves, it and the rest of the async method gets added to the microtask queue for handling? I know that async/await is syntactic sugar for the Promise API, so I’m assuming that this is sorta what happens, but I want to make sure I’m really understanding the “magic” that happens when an await is reached.

From what I’ve read, this seems to be what’s done in C#, but I’m not exactly sure how it translates to JS.

答:
It is exactly as you said, it puts the rest of the function into a micro task Q, and returns the main function.

Then when the promise resolves, it executes the async part.

What helps me to understand it is to convert the async/await into promise syntax, and then it gets clear.

For example:

```<code>async function doSomthing() {
  someSync();

  const result1 = await someAsync();
  const result2 = await someAsync2();

  return result1 + result2;
}
</code>```

"converts" to:

```<code>function doSomthing() {
  someSync();

  return someAsync().then(result1 => {
    return someAsync2().then(result2 => {
      return result1 + result2;
    });
  });
}
</code>```

You can see that doSomthing immediately returns the promise.

Body:
It is exactly as you said, it puts the rest of the function into a micro task Q, and returns the main function.

Then when the promise resolves, it executes the async part.

What helps me to understand it is to convert the async/await into promise syntax, and then it gets clear.

For example:

async function doSomthing() {
  someSync();

  const result1 = await someAsync();
  const result2 = await someAsync2();

  return result1 + result2;
}

"converts" to:

function doSomthing() {
  someSync();

  return someAsync().then(result1 => {
    return someAsync2().then(result2 => {
      return result1 + result2;
    });
  });
}

You can see that doSomthing immediately returns the promise.


问:
How to process binary data from API Gateway in Lambda and vice-versa?
I'm currently have the following setup:
1. S3 Bucket
2. API Gateway with GET/POST resource
3. Two Lambda Functions (one for getting data from s3, one for storing data to s3)

For example the GET Resource, i pass a key parameter, which is used in the lambda function to get the object from s3 bucket. then i want to return the retrieved object to api gateway and to client as a binary.

In the POST resource, i want to send a binary payload, eg.: pdf or zip file, save it to s3 and return generated key.

So on one hand i want my api gateway and lambda to be able return binary data in GET request, on the other hand i want it to accept binary payload in POST request.

In api gateway settings, i've set Binary-Media-Types to application/octet-stream. Also i have lambda proxy integration activated.

My question is: How can I process binary data in api gateway/lambda?

I tried messing around with Headers and Content-Types but more or less i didn't know what I was doing :(

Example store-luggage lambda for storing data from POST request in S3

```<code>import boto3
import json
import uuid
import logging
from botocore.exceptions import ClientError

def lambda_handler(event, context):

    #data = <binary data from POST request>?

    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    bucket = 'bucket1'

    uniqueid = str(uuid.uuid4())
    logger.info("Generated UUID: " + uniqueid)

    s3 = boto3.resource('s3')

    logger.info("Trying to save file '" + uniqueid + "' to bucket '" + bucket + "'")

    savedObj = None

    try:
        savedObj = s3.Bucket(bucket).put_object(Key=uniqueid, Body=<here should be my binary payload from POST request>)
    except ClientError as e:
        logger.error("Saving of object has failed: " + str(e.response['Error']['Message']))

    if savedObj is None:
        return {
            'statusCode': 500,
            'body': json.dumps({
                'message': 'Saving of object has failed!'
            })
        }

    return {
        'statusCode': 200,
        'body': json.dumps({
            'token': uniqueid
        })
    }
</code>```

get-luggage lambda for retrieving object from s3 by given key and return binary payload in response

```<code>import boto3
import json
from pprint import pprint
from botocore.exceptions import ClientError
import logging

def lambda_handler(event, context):

    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    bucket = 'bucket1'
    token = event["queryStringParameters"]["token"]

    s3 = boto3.client('s3')

    objectFromS3 = None

    try:
        objectFromS3 = s3.get_object(Bucket=bucket, Key=token)
    except ClientError as ex:
        if ex.response['Error']['Code'] == 'NoSuchKey':
            logger.info('No object found - returning empty')
        else:
            raise ex

    if objectFromS3 is None:
        return {
            'statusCode': 404,
            'body': json.dumps({
                'message': 'Cannot retrieve object from storage!'
            })
        }

    pprint(objectFromS3)
    #ContentType application/octet-stream

    return {
        'statusCode': 200,
        'body' : <binary data from retrieved s3 object here?>,
        'headers': {
            'content-type': 'application/octet-stream'
        },
        'isBase64Encoded': True
    }
</code>```

I expected to retrieve binary payload in GET response and expected api gateway to pass binary payload from POST request to lambda, but none of this was achieved with the stuff i tried.

I hope i descriped my problem well enough, if any clearification is needed let me know.

best wishes,
an aws noob

答:
First, you need to configure the MIME types that you expect to treat as binary data in API gateway settings.

Settings -> Binary Media Types.

Specify the exact MIME type to use as binary data application/pdf, application/zip etc. application/octet-stream is representing generic data which exact type is unknown.

In your Http request, there should be Accept header indicating which MIME type includes in the payload.

Accept: application/pdf

Accept: application/zip

Since the AWS Lambda process requests and responses as base64 encoded, you should decode POST request body and get original binary content before uploaded into S3 bucket.

After fetching data from S3 bucket lambda encodes binary data before sending it to API gateway. In response, you should set the value of the isBase64Encoded flag to True. Then API gateway performs Base64 decoding on encoded data before sending it to the client if Http request includes corresponding Accept header.

Body:
I'm currently have the following setup:
1. S3 Bucket
2. API Gateway with GET/POST resource
3. Two Lambda Functions (one for getting data from s3, one for storing data to s3)

For example the GET Resource, i pass a key parameter, which is used in the lambda function to get the object from s3 bucket. then i want to return the retrieved object to api gateway and to client as a binary.

In the POST resource, i want to send a binary payload, eg.: pdf or zip file, save it to s3 and return generated key.

So on one hand i want my api gateway and lambda to be able return binary data in GET request, on the other hand i want it to accept binary payload in POST request.

In api gateway settings, i've set Binary-Media-Types to application/octet-stream. Also i have lambda proxy integration activated.

My question is: How can I process binary data in api gateway/lambda?

I tried messing around with Headers and Content-Types but more or less i didn't know what I was doing :(

Example store-luggage lambda for storing data from POST request in S3

import boto3
import json
import uuid
import logging
from botocore.exceptions import ClientError

def lambda_handler(event, context):

    #data = <binary data from POST request>?

    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    bucket = 'bucket1'

    uniqueid = str(uuid.uuid4())
    logger.info("Generated UUID: " + uniqueid)

    s3 = boto3.resource('s3')

    logger.info("Trying to save file '" + uniqueid + "' to bucket '" + bucket + "'")

    savedObj = None

    try:
        savedObj = s3.Bucket(bucket).put_object(Key=uniqueid, Body=<here should be my binary payload from POST request>)
    except ClientError as e:
        logger.error("Saving of object has failed: " + str(e.response['Error']['Message']))

    if savedObj is None:
        return {
            'statusCode': 500,
            'body': json.dumps({
                'message': 'Saving of object has failed!'
            })
        }

    return {
        'statusCode': 200,
        'body': json.dumps({
            'token': uniqueid
        })
    }

get-luggage lambda for retrieving object from s3 by given key and return binary payload in response

import boto3
import json
from pprint import pprint
from botocore.exceptions import ClientError
import logging

def lambda_handler(event, context):

    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    bucket = 'bucket1'
    token = event["queryStringParameters"]["token"]

    s3 = boto3.client('s3')

    objectFromS3 = None

    try:
        objectFromS3 = s3.get_object(Bucket=bucket, Key=token)
    except ClientError as ex:
        if ex.response['Error']['Code'] == 'NoSuchKey':
            logger.info('No object found - returning empty')
        else:
            raise ex

    if objectFromS3 is None:
        return {
            'statusCode': 404,
            'body': json.dumps({
                'message': 'Cannot retrieve object from storage!'
            })
        }

    pprint(objectFromS3)
    #ContentType application/octet-stream

    return {
        'statusCode': 200,
        'body' : <binary data from retrieved s3 object here?>,
        'headers': {
            'content-type': 'application/octet-stream'
        },
        'isBase64Encoded': True
    }

I expected to retrieve binary payload in GET response and expected api gateway to pass binary payload from POST request to lambda, but none of this was achieved with the stuff i tried.

I hope i descriped my problem well enough, if any clearification is needed let me know.

best wishes,
an aws noob


问:
Sql select query with several subqueries optimization
I have MySql database with such tables:

```<code>PageviewEvents:
pageviewId | eventId | eventValue | eventTime

SessionPageviews:
id | sessionId | page
</code>```

PageviewEvents.pageviewId is a refers to SessionPageviews.id as foreign key.

When I need to select some data by eventId, I use this query:

```<code>SELECT
    sp.page as Page, count(*)
from PageviewEvents pe
left join SessionPageviews sp on sp.id = pe.pageviewId
where pe.eventId = 1
GROUP by sp.page
order BY 2 DESC
</code>```

And get a table like this:

```<code>page | count_of_event_1
</code>```

But now I need to select more data:

```<code>page | count_of_event_1 | count_of_event_2 ... | count_of_event_N
</code>```

I started with 2 events and tried to white something like this:

```<code>SELECT
    sp.page as Page,
    (SELECT count(*) from PageviewEvents pe1 left join SessionPageviews sp1 on sp1.id = pe1.pageviewId where pe1.eventId = 1 and sp1.page = sp.page) as count_of_event_1,
    (SELECT count(*) from PageviewEvents pe1 left join SessionPageviews sp1 on sp1.id = pe1.pageviewId where pe1.eventId = 2 and sp1.page = sp.page) as count_of_event_2
from PageviewEvents pe
left join SessionPageviews sp on sp.id = pe.pageviewId
where pe.eventId = 1 OR pe.eventId = 2
GROUP by sp.page
order BY 2 DESC
</code>```

When I run this query on remote server, it freezes.

Are there any errors in my query? How to optimize it?

答:
You could try using conditional aggregation:

```<code>SELECT
    sp.page AS Page,
    COUNT(CASE WHEN pe.eventId = 1 THEN 1 END) AS count_of_event_1,
    COUNT(CASE WHEN pe.eventId = 2 THEN 1 END) AS count_of_event_2
FROM PageviewEvents pe
LEFT JOIN SessionPageviews sp
    ON sp.id = pe.pageviewId
WHERE
    pe.eventId IN (1, 2)
GROUP BY
    sp.page
ORDER BY
    2 DESC;
</code>```

Beyond the above, you may consider adding the following index to your table:

```<code>CREATE INDEX idx ON SessionPageviews (pageviewId, eventId);
</code>```

This might help speed up the join between the two tables.

Body:
I have MySql database with such tables:

PageviewEvents:
pageviewId | eventId | eventValue | eventTime

SessionPageviews:
id | sessionId | page

PageviewEvents.pageviewId is a refers to SessionPageviews.id as foreign key.

When I need to select some data by eventId, I use this query:

SELECT
    sp.page as Page, count(*)
from PageviewEvents pe
left join SessionPageviews sp on sp.id = pe.pageviewId
where pe.eventId = 1
GROUP by sp.page
order BY 2 DESC

And get a table like this:

page | count_of_event_1

But now I need to select more data:

page | count_of_event_1 | count_of_event_2 ... | count_of_event_N

I started with 2 events and tried to white something like this:

SELECT
    sp.page as Page,
    (SELECT count(*) from PageviewEvents pe1 left join SessionPageviews sp1 on sp1.id = pe1.pageviewId where pe1.eventId = 1 and sp1.page = sp.page) as count_of_event_1,
    (SELECT count(*) from PageviewEvents pe1 left join SessionPageviews sp1 on sp1.id = pe1.pageviewId where pe1.eventId = 2 and sp1.page = sp.page) as count_of_event_2
from PageviewEvents pe
left join SessionPageviews sp on sp.id = pe.pageviewId
where pe.eventId = 1 OR pe.eventId = 2
GROUP by sp.page
order BY 2 DESC

When I run this query on remote server, it freezes.

Are there any errors in my query? How to optimize it?

Body:
You could try using conditional aggregation:

SELECT
    sp.page AS Page,
    COUNT(CASE WHEN pe.eventId = 1 THEN 1 END) AS count_of_event_1,
    COUNT(CASE WHEN pe.eventId = 2 THEN 1 END) AS count_of_event_2
FROM PageviewEvents pe
LEFT JOIN SessionPageviews sp
    ON sp.id = pe.pageviewId
WHERE
    pe.eventId IN (1, 2)
GROUP BY
    sp.page
ORDER BY
    2 DESC;

Beyond the above, you may consider adding the following index to your table:

CREATE INDEX idx ON SessionPageviews (pageviewId, eventId);

This might help speed up the join between the two tables.


问:
How to center items in a Recyclerview?
I am using RecyclerView with Cardview items inside it. I set the  GridLayoutManager to show 2 items at each row and I want it to be centered on all phones like this :

expected result

But I have currently these :

Actual result

I tried different poor solutions (paddingLeft...) but it works on phones with bigger screens and doesn't work on smaller phones.

content_main.xml looks like this :

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools">

    <SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:queryHint="Rechercher un film"
        android:iconifiedByDefault="false"
        android:layout_marginTop="65dp"
        android:layout_marginBottom="10dp"
        android:layout_height="30dp" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/movies_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/searchView"
        android:scrollbars="vertical"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true" />

</RelativeLayout>
</code>```

movie_card.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<android.support.v7.widget.CardView
    android:id="@+id/cardView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="170dip"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/item_movie_poster"
            android:layout_width="170dip"
            android:layout_height="256dip"
            android:layout_centerHorizontal="true"
            android:contentDescription="@string/movie_image_description"
            android:scaleType="centerCrop" />

        <TextView
            android:id="@+id/item_movie_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/item_movie_poster"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="10dip"
            android:layout_marginTop="5dip"
            android:textSize="15sp"
            android:textAlignment="center"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:textStyle="bold" />

    </RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</code>```

And app_bar_main.xml which includes the content_main.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
In your movie_card.xml set width to match_parent and add gravity

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" //<-- change
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" //<-- add
android:orientation="vertical">
</code>```

Title: How to center items in a Recyclerview?

Body:
I am using RecyclerView with Cardview items inside it. I set the  GridLayoutManager to show 2 items at each row and I want it to be centered on all phones like this :

expected result

But I have currently these :

Actual result

I tried different poor solutions (paddingLeft...) but it works on phones with bigger screens and doesn't work on smaller phones.

content_main.xml looks like this :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools">

    <SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:queryHint="Rechercher un film"
        android:iconifiedByDefault="false"
        android:layout_marginTop="65dp"
        android:layout_marginBottom="10dp"
        android:layout_height="30dp" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/movies_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/searchView"
        android:scrollbars="vertical"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true" />

</RelativeLayout>

movie_card.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<android.support.v7.widget.CardView
    android:id="@+id/cardView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="170dip"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/item_movie_poster"
            android:layout_width="170dip"
            android:layout_height="256dip"
            android:layout_centerHorizontal="true"
            android:contentDescription="@string/movie_image_description"
            android:scaleType="centerCrop" />

        <TextView
            android:id="@+id/item_movie_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/item_movie_poster"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="10dip"
            android:layout_marginTop="5dip"
            android:textSize="15sp"
            android:textAlignment="center"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:textStyle="bold" />

    </RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

And app_bar_main.xml which includes the content_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

Body:
In your movie_card.xml set width to match_parent and add gravity

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" //<-- change
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" //<-- add
android:orientation="vertical">


答:
If you were running a test with this code you should have seen an exception with the following message being thrown by JUnit:

Method tearDown() should not be static

Method annotated with JUnit test annotations should always be non-static and located inside dedicated classes used exclusively for running tests. Use the following code as a base to further build your test class:

```<code>import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class SeleniumTest {

    @Before
    public void prepareBrowserForSelenium() throws Exception {
        System.out.println("Running method annotated with @Before");
    }

    @Test
    public void DuringTest() throws Exception {
        System.out.println("Running main test method");
    }

    @After
    public static void tearDown() throws Exception {
        System.out.println("Running method annotated with @After");
    }
}
</code>```

Console output:

```<code>Running method annotated with @Before
Running main test method
Running method annotated with @After
</code>```

As you see everything work just fine. I would suggest reading more about JUnit testing in general and here is a good place to start:
https://github.com/junit-team/junit4/wiki/Getting-started

Title: JUnit Annotations not being run through

Body:
If you were running a test with this code you should have seen an exception with the following message being thrown by JUnit:

Method tearDown() should not be static

Method annotated with JUnit test annotations should always be non-static and located inside dedicated classes used exclusively for running tests. Use the following code as a base to further build your test class:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class SeleniumTest {

    @Before
    public void prepareBrowserForSelenium() throws Exception {
        System.out.println("Running method annotated with @Before");
    }

    @Test
    public void DuringTest() throws Exception {
        System.out.println("Running main test method");
    }

    @After
    public static void tearDown() throws Exception {
        System.out.println("Running method annotated with @After");
    }
}

Console output:

Running method annotated with @Before
Running main test method
Running method annotated with @After

As you see everything work just fine. I would suggest reading more about JUnit testing in general and here is a good place to start:
https://github.com/junit-team/junit4/wiki/Getting-started


问:
How to pass two different objects to a POST request in postman to test RESTful API?
This is actually a two part question, one is, how to pass two JSON objects, anther one is how to create object from two different classand pass that object to a POST method.

I am trying to test a POST method of RESTful API by passing two different objects in postman. I could successfully test only a POST method with one object, but when I am trying to send two different object to POST method where two different objects  , postman say's bad request.

Here is my two entity class: First one is Cleint class:

```<code>import lombok.Data;
import org.zevgma.api.entities.user.User;

import javax.persistence.*;
import java.util.Date;

@Data
@Entity
@Table(name = "client")
public class Client {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_pk_generator")
    @SequenceGenerator(name = "user_pk_generator", sequenceName = "users_user_id_seq", allocationSize = 1)
    @Column(name = "id", unique = true, nullable = false,  columnDefinition = "serial")
    private int id;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(nullable = false)
    private String email;

    @Column(nullable = false)
    private Date userDateCreate;

 }
</code>```

Second one is about ClientAddress:

```<code>import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Data
@Entity
public class ClientAddress {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private int streetID;
    private String streetName;
    private int streetNumber;
}
</code>```

I have tried different POST request with JSON objets or JSON nested threads in Stackoverflow and youtube, but could not find my solution.
Spceially I have tried instructions from these threads:

https://it.mathworks.com/help/thingspeak/bulkwritejsondata.html

Post Multiple JSON Objects Simultaneously with Express and Postman

Here is the POST method of RESTful API which one I want to test:

```<code>@PostMapping(value = "/api/employees", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> createClient(@RequestBody Client client,
                                           @RequestBody ClientAddress clientAddress){
    clientService.save(client);
    clientAddressService.save(clientAddress);
    return new ResponseEntity<>(client.getName() + " and "+ clientAddress.getStreetName() + " successfully added",
            HttpStatus.OK);
}
</code>```

So far I have tried with this JSON object:

[
{
     "name": "Bilbo",
      "email": "bilbo@gmail.com"
    },

  {
     "streetName": "Central Street",
     "streetNumber": "31"
   }
]```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>[
 {
  "client":{
               "name": "Bilbo",
                "email": "bilbo@gmail.com"
              },

  "clientAddress":{
                      "streetName": "Central Street",
                      "streetNumber": "31"
                     }
   }
]</code>```

By Pre-Request Script:

 //Pre-request Script
 var client = {
     "name": "Bilbo",
     "email": "bilbo@mail.com"
 }

var address = {
    "streetName": "New Street",
    "streetNumber": "3"
}

pm.environment.set("client", JSON.stringify(client));
pm.environment.set("address", JSON.stringify(address));

//Body
[
{{client}},{{address}}
]```
</div>
</div>
</p>

<p>Now the second part of questions: What if I want to create a new object, ClientData from the above two mentioned class, Client and ClientAddress and pass this ClientData object to a POST method, how to do it.</p>

<p>Here is the ClientData class:</p>

<p>import lombok.Data;</p>

```@Data
public class ClientData {

    private Client client;
    private ClientAddress address;
}
```

<p>And here is the POST method where I want to pass a ClientData object:</p>

```  @PostMapping(value = "/api/employees", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> createClient(@RequestBody ClientData clientData){
               Client client = clientData.getClient();
                clientService.save(client);
            ClientAddress clientAddress = clientData.getAddress();
            clientAddressService.save(clientAddress);

        return new ResponseEntity<>(client.getName() + " and "+ clientAddress.getStreetName() + " successfully added",
                HttpStatus.OK);
    }
```

To test method in postman I should create these complex ClientData JSON object and how to pass the it?

答:
Instead of doing this in the body:

```<code>[{{client}}, {{address}}]
</code>```

Replace it with this:

```<code>{{requestBody}}
</code>```

Now, store the complete body in an environment variable.
Remove the separate variables for client and address and just use a single variable.

So, update your pre-request script to something like this:

```<code>pm.environment.set("requestBody", JSON.stringify([client, address]));
</code>```

Body:
This is actually a two part question, one is, how to pass two JSON objects, anther one is how to create object from two different classand pass that object to a POST method.

I am trying to test a POST method of RESTful API by passing two different objects in postman. I could successfully test only a POST method with one object, but when I am trying to send two different object to POST method where two different objects  , postman say's bad request.

Here is my two entity class: First one is Cleint class:

import lombok.Data;
import org.zevgma.api.entities.user.User;

import javax.persistence.*;
import java.util.Date;

@Data
@Entity
@Table(name = "client")
public class Client {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_pk_generator")
    @SequenceGenerator(name = "user_pk_generator", sequenceName = "users_user_id_seq", allocationSize = 1)
    @Column(name = "id", unique = true, nullable = false,  columnDefinition = "serial")
    private int id;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(nullable = false)
    private String email;

    @Column(nullable = false)
    private Date userDateCreate;

 }

Second one is about ClientAddress:

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Data
@Entity
public class ClientAddress {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private int streetID;
    private String streetName;
    private int streetNumber;
}

I have tried different POST request with JSON objets or JSON nested threads in Stackoverflow and youtube, but could not find my solution.
Spceially I have tried instructions from these threads:

https://it.mathworks.com/help/thingspeak/bulkwritejsondata.html

Post Multiple JSON Objects Simultaneously with Express and Postman

Here is the POST method of RESTful API which one I want to test:

@PostMapping(value = "/api/employees", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> createClient(@RequestBody Client client,
                                           @RequestBody ClientAddress clientAddress){
    clientService.save(client);
    clientAddressService.save(clientAddress);
    return new ResponseEntity<>(client.getName() + " and "+ clientAddress.getStreetName() + " successfully added",
            HttpStatus.OK);
}

So far I have tried with this JSON object:

[
{
     "name": "Bilbo",
      "email": "bilbo@gmail.com"
    },

  {
     "streetName": "Central Street",
     "streetNumber": "31"
   }
]

[
 {
  "client":{
               "name": "Bilbo",
                "email": "bilbo@gmail.com"
              },

  "clientAddress":{
                      "streetName": "Central Street",
                      "streetNumber": "31"
                     }
   }
]

By Pre-Request Script:

 //Pre-request Script
 var client = {
     "name": "Bilbo",
     "email": "bilbo@mail.com"
 }

var address = {
    "streetName": "New Street",
    "streetNumber": "3"
}

pm.environment.set("client", JSON.stringify(client));
pm.environment.set("address", JSON.stringify(address));

//Body
[
{{client}},{{address}}
]

Now the second part of questions: What if I want to create a new object, ClientData from the above two mentioned class, Client and ClientAddress and pass this ClientData object to a POST method, how to do it.

Here is the ClientData class:

import lombok.Data;

@Data
public class ClientData {

    private Client client;
    private ClientAddress address;
}

And here is the POST method where I want to pass a ClientData object:

  @PostMapping(value = "/api/employees", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> createClient(@RequestBody ClientData clientData){
               Client client = clientData.getClient();
                clientService.save(client);
            ClientAddress clientAddress = clientData.getAddress();
            clientAddressService.save(clientAddress);

        return new ResponseEntity<>(client.getName() + " and "+ clientAddress.getStreetName() + " successfully added",
                HttpStatus.OK);
    }

To test method in postman I should create these complex ClientData JSON object and how to pass the it?

Body:
Instead of doing this in the body:

[{{client}}, {{address}}]

Replace it with this:

{{requestBody}}

Now, store the complete body in an environment variable.
Remove the separate variables for client and address and just use a single variable.

So, update your pre-request script to something like this:

pm.environment.set("requestBody", JSON.stringify([client, address]));


问:
Multicolor marker with matplotlib plot
I am trying to plot a simple chart with markers as "x" (green colour) if datapoint is even and "o" (red color) if datapoint is odd.  However the chart is rendered with all markers as "o" except the last which is correctly showing as "x".  Pls guide.</p>

```<code>import matplotlib.pyplot as plt

a = []
b = []

for i in range( 1, 11 ):
    a.append( i )
    b.append( i )
    if ( i % 2 ) == 0:
            plt.plot( a, b, "gx" )
    else:
            plt.plot( a, b, "ro" )

plt.show()
</code>```

答:
If you look carefully, the first markers are not red "o"'s, but red circles with a green "x" inside. The for loop you made is equivalent to:

```<code>plt.plot([1], [1], "ro")
plt.plot([1, 2], [1, 2], "gx")
plt.plot([1, 2, 3], [1, 2, 3], "ro")
(...)
</code>```

As a consequence, you will plot 10 different graphics (technically lines.Lines2D objects). The last object you plot, for i=10, is "gx"; it ends up on top of the others.

Here's a corrected version of your algorithm (make one plot per point):

```<code># Not a good way to go about it
import matplotlib.pyplot as plt

# Loop, one plot per iteration
for i in range(1,11):
    if i % 2 == 0:
        plt.plot(i, i, "gx")
    else:
        plt.plot(i, i, "ro")

plt.show()
</code>```

Here's a better algorithm, though:

```<code># use this one instead
import matplotlib.pyplot as plt

# Generate a, b outside the body of the loop
a = list(range(1,11))
b = list(range(1,11))

# Make one plot per condition branch
# See also https://stackoverflow.com/questions/509211/understanding-slice-notation
plt.plot(a[0::2], b[0::2], "gx")
plt.plot(a[1::2], b[1::2], "ro")

plt.show()
</code>```

Title: Multicolor marker with matplotlib plot

Body:
I am trying to plot a simple chart with markers as "x" (green colour) if datapoint is even and "o" (red color) if datapoint is odd.  However the chart is rendered with all markers as "o" except the last which is correctly showing as "x".  Pls guide.

import matplotlib.pyplot as plt

a = []
b = []

for i in range( 1, 11 ):
    a.append( i )
    b.append( i )
    if ( i % 2 ) == 0:
            plt.plot( a, b, "gx" )
    else:
            plt.plot( a, b, "ro" )

plt.show()

Body:
If you look carefully, the first markers are not red "o"'s, but red circles with a green "x" inside. The for loop you made is equivalent to:

plt.plot([1], [1], "ro")
plt.plot([1, 2], [1, 2], "gx")
plt.plot([1, 2, 3], [1, 2, 3], "ro")
(...)

As a consequence, you will plot 10 different graphics (technically lines.Lines2D objects). The last object you plot, for i=10, is "gx"; it ends up on top of the others.

Here's a corrected version of your algorithm (make one plot per point):

# Not a good way to go about it
import matplotlib.pyplot as plt

# Loop, one plot per iteration
for i in range(1,11):
    if i % 2 == 0:
        plt.plot(i, i, "gx")
    else:
        plt.plot(i, i, "ro")

plt.show()

Here's a better algorithm, though:

# use this one instead
import matplotlib.pyplot as plt

# Generate a, b outside the body of the loop
a = list(range(1,11))
b = list(range(1,11))

# Make one plot per condition branch
# See also https://stackoverflow.com/questions/509211/understanding-slice-notation
plt.plot(a[0::2], b[0::2], "gx")
plt.plot(a[1::2], b[1::2], "ro")

plt.show()


问:
Adding a tooltip to a ComboBox in Excel with VBA
I've added two Dropdown (aka ComboBox) to a Sheet

Using this piece of code I can access the Dropdown but how can I add a tooltip on the Dropdown?

The best solution would be to show a different text for every item but if there is only an unique tooltip for the whole dropdown I can change it after selecting every item.

```<code>Sub DropDown1_Change()

    Dim s As Object
    Set s = ActiveSheet.Shapes(Application.Caller)
    s.ToolTip = "Example"
    Debug.Print s.ControlFormat.Value

End Sub
</code>```

答:
Following is my code:</p>

```<code>Private Sub ComboBox1_Click()
   ' Adding new items
   ComboBox1.AddItem ("S")
   ComboBox1.AddItem ("M")

   If ComboBox1.Text = "S" Then  'Add your dropdown item here
   With Me.ComboBox1
   .ControlTipText = "Strong"  ' Add your text here
   End With
   End If
   If ComboBox1.Text = "M" Then   'Add your dropdown item here
   With Me.ComboBox1
   .ControlTipText = "Moderate" ' Add your text here
   End With
   End If

End Sub
</code>```

Body:
I've added two Dropdown (aka ComboBox) to a Sheet

Using this piece of code I can access the Dropdown but how can I add a tooltip on the Dropdown?

The best solution would be to show a different text for every item but if there is only an unique tooltip for the whole dropdown I can change it after selecting every item.

Sub DropDown1_Change()

    Dim s As Object
    Set s = ActiveSheet.Shapes(Application.Caller)
    s.ToolTip = "Example"
    Debug.Print s.ControlFormat.Value

End Sub

Body:
Following is my code:

Private Sub ComboBox1_Click()
   ' Adding new items
   ComboBox1.AddItem ("S")
   ComboBox1.AddItem ("M")

   If ComboBox1.Text = "S" Then  'Add your dropdown item here
   With Me.ComboBox1
   .ControlTipText = "Strong"  ' Add your text here
   End With
   End If
   If ComboBox1.Text = "M" Then   'Add your dropdown item here
   With Me.ComboBox1
   .ControlTipText = "Moderate" ' Add your text here
   End With
   End If

End Sub


问:
How to fix gradient transition on hover
I'm currently working on a hover transition from background to background gradient. But I want it to change the table row but instead it changes the whole background of the table.

Here's JSFiddle to show what happens when you hover on the table row

I've tried using display block which changes the table row background with a transition but then it messes up my whole table row.

The background of the table changes but is has to change the table row only.

.container #table {
  width: 100%;
  font-weight: bold;
  border-spacing: 0px 15px;
}
.container #table tr {
  position: relative;
  background-color: #273240;
  z-index: 1;
}
.container #table tr::before {
  position: absolute;
  content: "";
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to right, #0089e0, #c0c1c1);
  z-index: -1;
  transition: opacity 0.5s linear;
  opacity: 0;
}
.container #table tr:hover::before {
  opacity: 1;
}
.container #table tr th {
  height: 35px;
  font-size: 10px;
  text-align: left;
  font-weight: bold;
  text-transform: uppercase;
  background-color: #273240;
}
.container #table tr th:nth-child(n+5) {
  width: 75px;
}
.container #table tr td {
  padding: 0px;
  font-size: 12px;
  font-style: italic;
}
.container #table tr td:first-child {
  width: 25px;
  font-style: normal;
  font-weight: 500;
  padding-left: 25px;
}
.container #table tr td div {
  max-height: 70px;
  padding: 25px 0px;
  transition: max-height 0.5s, padding 0.5s;
}
.container #table tr td i {
  font-size: 12px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<table id="table">
  <tr>
    <th></th>
    <th>POS</th>
    <th>TEAM</th>
    <th>DRIVER</th>
    <th>MUG</th>
    <th>SPA</th>
    <th>BRN</th>
    <th>POR</th>
    <th>BAR</th>
    <th>TOT</th>
  </tr>
  <tbody>
    <tr>
      <td></td>
      <td>1ST</td>
      <td>PROSPORT PERFORMANCE (85)</td>
      <td>ROBERT RENAUER</td>
      <td>24</td>
      <td>28</td>
      <td>33</td>
      <td>-</td>
      <td>-</td>
      <td>85</td>
    </tr>
  </tbody>
</table>
</div></code>```

答:
Make the background and the pseudo element on th/td instead and use background-attachment:fixed to simulate a continuous background:

.container #table {
  width: 100%;
  font-weight: bold;
  border-spacing: 0px 15px;
}
.container #table tr >* {
  position: relative;
  background-color: #273240;
  z-index: 1;
}
.container #table tr > *::before {
  position: absolute;
  content: "";
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to right, #0089e0, #c0c1c1) fixed;
  z-index: -1;
  transition: opacity 0.5s linear;
  opacity: 0;
}
.container #table tr:hover > *::before {
  opacity: 1;
}
.container #table tr th {
  height: 35px;
  font-size: 10px;
  text-align: left;
  font-weight: bold;
  text-transform: uppercase;
  background-color: #273240;
}
.container #table tr th:nth-child(n+5) {
  width: 75px;
}
.container #table tr td {
  padding: 0px;
  font-size: 12px;
  font-style: italic;
}
.container #table tr td:first-child {
  width: 25px;
  font-style: normal;
  font-weight: 500;
  padding-left: 25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<table id="table">
  <tr>
    <th></th>
    <th>POS</th>
    <th>TEAM</th>
    <th>DRIVER</th>
    <th>MUG</th>
    <th>SPA</th>
    <th>BRN</th>
    <th>POR</th>
    <th>BAR</th>
    <th>TOT</th>
  </tr>
  <tbody>
    <tr>
      <td></td>
      <td>1ST</td>
      <td>PROSPORT PERFORMANCE (85)</td>
      <td>ROBERT RENAUER</td>
      <td>24</td>
      <td>28</td>
      <td>33</td>
      <td>-</td>
      <td>-</td>
      <td>85</td>
    </tr>
  </tbody>
</table>
</div></code>```

Title: How to fix gradient transition on hover

Body:
I'm currently working on a hover transition from background to background gradient. But I want it to change the table row but instead it changes the whole background of the table.

Here's JSFiddle to show what happens when you hover on the table row

I've tried using display block which changes the table row background with a transition but then it messes up my whole table row.

The background of the table changes but is has to change the table row only.

.container #table {
  width: 100%;
  font-weight: bold;
  border-spacing: 0px 15px;
}
.container #table tr {
  position: relative;
  background-color: #273240;
  z-index: 1;
}
.container #table tr::before {
  position: absolute;
  content: "";
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to right, #0089e0, #c0c1c1);
  z-index: -1;
  transition: opacity 0.5s linear;
  opacity: 0;
}
.container #table tr:hover::before {
  opacity: 1;
}
.container #table tr th {
  height: 35px;
  font-size: 10px;
  text-align: left;
  font-weight: bold;
  text-transform: uppercase;
  background-color: #273240;
}
.container #table tr th:nth-child(n+5) {
  width: 75px;
}
.container #table tr td {
  padding: 0px;
  font-size: 12px;
  font-style: italic;
}
.container #table tr td:first-child {
  width: 25px;
  font-style: normal;
  font-weight: 500;
  padding-left: 25px;
}
.container #table tr td div {
  max-height: 70px;
  padding: 25px 0px;
  transition: max-height 0.5s, padding 0.5s;
}
.container #table tr td i {
  font-size: 12px;
}

    POS
    TEAM
    DRIVER
    MUG
    SPA
    BRN
    POR
    BAR
    TOT

      1ST
      PROSPORT PERFORMANCE (85)
      ROBERT RENAUER
      24
      28
      33
      -
      -
      85

Body:
Make the background and the pseudo element on th/td instead and use background-attachment:fixed to simulate a continuous background:

.container #table {
  width: 100%;
  font-weight: bold;
  border-spacing: 0px 15px;
}
.container #table tr >* {
  position: relative;
  background-color: #273240;
  z-index: 1;
}
.container #table tr > *::before {
  position: absolute;
  content: "";
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to right, #0089e0, #c0c1c1) fixed;
  z-index: -1;
  transition: opacity 0.5s linear;
  opacity: 0;
}
.container #table tr:hover > *::before {
  opacity: 1;
}
.container #table tr th {
  height: 35px;
  font-size: 10px;
  text-align: left;
  font-weight: bold;
  text-transform: uppercase;
  background-color: #273240;
}
.container #table tr th:nth-child(n+5) {
  width: 75px;
}
.container #table tr td {
  padding: 0px;
  font-size: 12px;
  font-style: italic;
}
.container #table tr td:first-child {
  width: 25px;
  font-style: normal;
  font-weight: 500;
  padding-left: 25px;
}

<div class="container">
<table id="table">
  <tr>
    <th></th>
    <th>POS</th>
    <th>TEAM</th>
    <th>DRIVER</th>
    <th>MUG</th>
    <th>SPA</th>
    <th>BRN</th>
    <th>POR</th>
    <th>BAR</th>
    <th>TOT</th>
  </tr>
  <tbody>
    <tr>
      <td></td>
      <td>1ST</td>
      <td>PROSPORT PERFORMANCE (85)</td>
      <td>ROBERT RENAUER</td>
      <td>24</td>
      <td>28</td>
      <td>33</td>
      <td>-</td>
      <td>-</td>
      <td>85</td>
    </tr>
  </tbody>
</table>
</div>


问:
Trying to Add a CollectionView to ResuableView Header like Instagram or SNapchat
I want to have a CollectionView in my Header that resembles that on Instagram and Snapchat for my main CollectionView which would be the feed. When I try to add the collectionview from the library and set the header as delegate and datasource after implementing the delegate methods, I still dont see anything in the header.</p>

```<code>    //let layout = UICollectionViewFlowLayout()

    let headerCollection = UICollectionView(frame: CGRect(x: 0, y: 0, width: 50, height: 90), collectionViewLayout: UICollectionViewFlowLayout())

    override func awakeFromNib() {
        super.awakeFromNib()

//       headerCollection.delegate = self
//        headerCollection.dataSource = self
    }

}

extension HeaderforFeed: UICollectionViewDataSource, UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CollectionViewData.Dict_StrImg.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = UICollectionViewCell(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        cell.backgroundColor = .red
        return cell
    }

}```
</code>```

答:
Based on your code, I would think that the issue is you are not adding it to the header (I understand it as a header section inside your UICollectionView). If it's so, try add it at

```<code>func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

}
</code>```

Here, you would add your custom view with UICollectionView as UICollectionReusableView

I don't know if this could help you, but according to your question is what I understood

Body:
I want to have a CollectionView in my Header that resembles that on Instagram and Snapchat for my main CollectionView which would be the feed. When I try to add the collectionview from the library and set the header as delegate and datasource after implementing the delegate methods, I still dont see anything in the header.

    //let layout = UICollectionViewFlowLayout()

    let headerCollection = UICollectionView(frame: CGRect(x: 0, y: 0, width: 50, height: 90), collectionViewLayout: UICollectionViewFlowLayout())

    override func awakeFromNib() {
        super.awakeFromNib()

//       headerCollection.delegate = self
//        headerCollection.dataSource = self
    }

}

extension HeaderforFeed: UICollectionViewDataSource, UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CollectionViewData.Dict_StrImg.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = UICollectionViewCell(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        cell.backgroundColor = .red
        return cell
    }

}```

Body:
Based on your code, I would think that the issue is you are not adding it to the header (I understand it as a header section inside your UICollectionView). If it's so, try add it at

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

}

Here, you would add your custom view with UICollectionView as UICollectionReusableView

I don't know if this could help you, but according to your question is what I understood


问:
bash scripting: Can I get sed to output the original line, then a space, then the modified line?
I'm new to Unix in all its forms, so please go easy on me!
I have a bash script that will pipe an ls command with arbitrary filenames into sed, which will use an arbitrary replacement pattern on the files, and then this will be piped into awk for some processing. The catch is, awk needs to know both the original file name and the new one.

I've managed everything except getting the original file names into awk. For instance, let's say my files are test.* and my replacement pattern is 's:es:ar;', which would change every occurrence of "test" to "tart". For testing purposes I'm just using awk to print what it's receiving:

```<code>ls "$@" | sed "$pattern" | awk '{printf "0: %s\n1: %s\n2: %s\n", $0,$1,$2}'
</code>```

where test.* is in $@ and the pattern is stored in $pattern.
Clearly, this doesn't get me to where I want to be. The output is obviously

```<code>0: tart.c
1: tart.c
2:
</code>```

If I could get sed to output "test.c tart.c", then I'd have two parameters for awk. I've played around with the pattern to no avail, even hardcoding "test.c" into the replacement. But of course that just gave me amateur results like "ttest.c art.c". Is it possible for sed to remember the input, then work it into the beginning of the output? Do I even have the right ideas? Thanks in advance!

答:
Use Perl instead of sed:

```<code>echo test.c | perl -lne 'print "$_ ", s/es/ar/r'
</code>```

-l removes the newline from input and adds it after each print. The /r modifier to the substitution returns the modified string instead of changing the variable (Perl 5.14+ needed).

Old answer, not working for s/t/b/2 or s/.*/replaced/2:

You can duplicate the contents of the line with s/.*/& &/, then just tell sed that it should only apply the second substitution (this works at least in GNU sed):

```<code>echo test.c | sed 's/.*/& &/; s/es/ar/2'
</code>```

Body:
I'm new to Unix in all its forms, so please go easy on me!
I have a bash script that will pipe an ls command with arbitrary filenames into sed, which will use an arbitrary replacement pattern on the files, and then this will be piped into awk for some processing. The catch is, awk needs to know both the original file name and the new one.

I've managed everything except getting the original file names into awk. For instance, let's say my files are test.* and my replacement pattern is 's:es:ar;', which would change every occurrence of "test" to "tart". For testing purposes I'm just using awk to print what it's receiving:

ls "$@" | sed "$pattern" | awk '{printf "0: %s\n1: %s\n2: %s\n", $0,$1,$2}'

where test.* is in $@ and the pattern is stored in $pattern.
Clearly, this doesn't get me to where I want to be. The output is obviously

0: tart.c
1: tart.c
2:

If I could get sed to output "test.c tart.c", then I'd have two parameters for awk. I've played around with the pattern to no avail, even hardcoding "test.c" into the replacement. But of course that just gave me amateur results like "ttest.c art.c". Is it possible for sed to remember the input, then work it into the beginning of the output? Do I even have the right ideas? Thanks in advance!

Body:
Use Perl instead of sed:

echo test.c | perl -lne 'print "$_ ", s/es/ar/r'

-l removes the newline from input and adds it after each print. The /r modifier to the substitution returns the modified string instead of changing the variable (Perl 5.14+ needed).

Old answer, not working for s/t/b/2 or s/.*/replaced/2:

You can duplicate the contents of the line with s/.*/& &/, then just tell sed that it should only apply the second substitution (this works at least in GNU sed):

echo test.c | sed 's/.*/& &/; s/es/ar/2'


问:
process data for new clients into data warehosue
we have a data warehouse we are processing incremental data for various clients on srvtimestamp based.currently we have open new clients with previous or historical transaction in OLTP i need to process data for New clients from day one .I need a dyanamic process which every time check the new clients and their srvtimestamp also to process data.

we are using Mysql Storedprocedures to incremental data loading which select max (srvtimestamp) from table and load data based on srvtimestamp

答:
You should use case statement in select like below.

```<code>select case new_client_flag = 'New' then  min(srvtimestamp) else max(srvtimestamp) end as 'srvtimestamp'
from table
</code>```

you should use flag for new_client_flag and update it after first processing if

```<code>new_client_flag = 'NEW'
</code>```

Body:
You should use case statement in select like below.

select case new_client_flag = 'New' then  min(srvtimestamp) else max(srvtimestamp) end as 'srvtimestamp'
from table

you should use flag for new_client_flag and update it after first processing if

new_client_flag = 'NEW'


问:
shiny 4 small textInput boxes side-by-side
I've got a shiny server version 0.4.0 and I want to have 4 small textInput boxes to look like this:

```<code>x-min x-max y-min y-max
[...] [...] [...] [...]
</code>```

They now look like this:

```<code>x-min
[...................]
x-max
[...................]
y-min
[...................]
y-max
[...................]
</code>```

With this code:

```<code>textInput(inputId="xlimitsmin", label="x-min", value = 0.0),
textInput(inputId="xlimitsmax", label="x-max", value = 0.5),
textInput(inputId="ylimitsmin", label="y-min", value = 0.5),
textInput(inputId="ylimitsmax", label="y-max", value = 1.0),
</code>```

Any ideas how to achieve this?

EDITED: I've successfully changed things like this elsewhere in the code:

```<code><style type="text/css">select#yaxis4 { height: 280px; width: 500px; }</style>
[... which links to this later on in the page...]
          <label class="control-label" for="yaxis4">Y-Axis</label>
          <select id="yaxis4" multiple="multiple">
</code>```

And this is what it looks like for the ones that don't work:

```<code><style type="text/css">select#xlimitsmax { display: inline-block; max-width: 50px; }</style>
[... which links to...]
          <label>x-max</label>
          <input id="xlimitsmax" type="text" value="0.5"/>
</code>```

EDITED:

Here is a self contained example ui.R that doesn't work:

```<code>library(shiny)
shinyUI(
pageWithSidebar(
  # application title
  headerPanel("test01"),
  sidebarPanel(
    tags$head(
      tags$style(type="text/css", "select { max-width: 360px; }"),
      tags$style(type="text/css", ".span4 { max-width: 360px; }"),
      tags$style(type="text/css",  ".well { max-width: 360px; }")
              ),
    wellPanel(
      p(strong("Side Panel:"))
             )
   ),
  mainPanel(
    textInput(inputId="xlimitsmin", label="x-min", value = 0.0),
    tags$head(tags$style(type="text/css", "select#xlimitsmin { max-width: 50px }")),
    textInput(inputId="xlimitsmax", label="x-max", value = 0.5),
    tags$head(tags$style(type="text/css", "select#xlimitsmax { display: inline-block; max-width: 50px; }"))
    )
))
</code>```

Resulting page:

答:
I wasn't happy with splitLayout() because it introduces scroll bars when space is limited.

I found that, at least for input widgets like buttons or text boxes, a quite easy solution with better responsive behaviour is using flex-box: (see this great guide: https://css-tricks.com/snippets/css/a-guide-to-flexbox/)

```<code>div(
  style = "display: flex; flex-wrap: wrap;",
  div(
    style = "flex: 1;",
    textInput("inputA", "The first input")
  ),
  div(
    style = "flex: 1;",
    textInput("inputB", "The second input")
  ),
  div(
    style = "flex: 1;",
    textInput("inputC", "The third input")
  )
)
</code>```

It is possible to adjust relative widths. Corresponding to splitLayout(cellWidths = c("25%", "75%"), ...):

```<code>div(
  style = "display: flex; flex-wrap: wrap;",
  div(
    style = "flex: 1;",
    textInput("inputA", "The first input")
  ),
  div(
    style = "flex: 3;", # second item 3 times as wide as first one
    textInput("inputB", "The second input")
  )
)
</code>```

Body:
I've got a shiny server version 0.4.0 and I want to have 4 small textInput boxes to look like this:

x-min x-max y-min y-max
[...] [...] [...] [...]

They now look like this:

x-min
[...................]
x-max
[...................]
y-min
[...................]
y-max
[...................]

With this code:

textInput(inputId="xlimitsmin", label="x-min", value = 0.0),
textInput(inputId="xlimitsmax", label="x-max", value = 0.5),
textInput(inputId="ylimitsmin", label="y-min", value = 0.5),
textInput(inputId="ylimitsmax", label="y-max", value = 1.0),

Any ideas how to achieve this?

EDITED: I've successfully changed things like this elsewhere in the code:

[... which links to this later on in the page...]
          Y-Axis
          <select id="yaxis4" multiple="multiple">

And this is what it looks like for the ones that don't work:

[... which links to...]
          x-max
          <input id="xlimitsmax" type="text" value="0.5"/>

EDITED:

Here is a self contained example ui.R that doesn't work:

library(shiny)
shinyUI(
pageWithSidebar(
  # application title
  headerPanel("test01"),
  sidebarPanel(
    tags$head(
      tags$style(type="text/css", "select { max-width: 360px; }"),
      tags$style(type="text/css", ".span4 { max-width: 360px; }"),
      tags$style(type="text/css",  ".well { max-width: 360px; }")
              ),
    wellPanel(
      p(strong("Side Panel:"))
             )
   ),
  mainPanel(
    textInput(inputId="xlimitsmin", label="x-min", value = 0.0),
    tags$head(tags$style(type="text/css", "select#xlimitsmin { max-width: 50px }")),
    textInput(inputId="xlimitsmax", label="x-max", value = 0.5),
    tags$head(tags$style(type="text/css", "select#xlimitsmax { display: inline-block; max-width: 50px; }"))
    )
))

Resulting page:

Body:
I wasn't happy with splitLayout() because it introduces scroll bars when space is limited.

I found that, at least for input widgets like buttons or text boxes, a quite easy solution with better responsive behaviour is using flex-box: (see this great guide: https://css-tricks.com/snippets/css/a-guide-to-flexbox/)

div(
  style = "display: flex; flex-wrap: wrap;",
  div(
    style = "flex: 1;",
    textInput("inputA", "The first input")
  ),
  div(
    style = "flex: 1;",
    textInput("inputB", "The second input")
  ),
  div(
    style = "flex: 1;",
    textInput("inputC", "The third input")
  )
)

It is possible to adjust relative widths. Corresponding to splitLayout(cellWidths = c("25%", "75%"), ...):

div(
  style = "display: flex; flex-wrap: wrap;",
  div(
    style = "flex: 1;",
    textInput("inputA", "The first input")
  ),
  div(
    style = "flex: 3;", # second item 3 times as wide as first one
    textInput("inputB", "The second input")
  )
)


问:
Financial Time Series Forecasting with Keras/Tensorflow: Three forecasting methods tried, three poor results had, what am I doing wrong?
I'm working with a dataset of a bunch of different features for stock forecasting for a project to help teach myself programming and to get into machine learning. I am running into some issues with predicting future data (or time series forecasting) and I was hoping someone out there could give  me some advice! Any advice or criticism you could provide will be greatly appreciated.

Below I've listed detailed examples of the three implementations I have tried for forecasting time series data. I could definitely be wrong on this but I don't believe this is mechanical code issue because all of the results are consistent despite me re-coding it a few times (the only thing I can really think of here is not using MinMaxScaler correctly. See closing thoughts). It could definitely, however, be a macrocoding mistake.

I didn't post any code for the project here because it was starting to turn into a wall of words and I had three separate examples, but if you have any questions or think it would benefit your assistance to see the code used for any of the below examples or the data used for all of them feel free to let me know and I'll link whatever's needed.

The three forecasting implementations I have tried:

1) - A sliding window implementation. Input data is shifted backwards in timesteps (x-1, x-2...), target data is current timestep (x). Data used for forecasting the first prediction is n-rows of test data shifted in same manner as input data. For every subsequent prediction the oldest timestep is removed and the prediction is appended to front of prediction row, maintaining the same number of total timesteps but progressing forward in time.

2) - Input data is just x, target data is shifted 30 timesteps forward for prediction (y+1, y+2 ... y+30). Attempting to forecast future by taking the first sample of x in test data and predicting 30 steps into the future with it.

3) - Combination of both methods, input data is shifted backward and in the example shown below, 101 timesteps including the present timestep (x-100, x-99 ... x) were used. Target data, similar to implementation 2, is shifted 30 timesteps into the future (y+1, y+2... y+30). With this, I am attempting to forecast the future by taking 101 timesteps of the first n-rows of test data and predicting 30 steps into the future from there.

For all tests, I cut off the end of my dataset at an arbitrary amount (last ~10% of total dataset), split everything before the cutoff into training/validation (80/20) and saved everything after the cutoff for testing & forecasting purposes.

As for network architectures, I've tried a bunch of different ones, from bidirectional LSTM to multi-input CNN / GRU, to a wavenet like CNN implementation and all produce prediction results that are bad in a similar enough way that I feel like this is either a data manipulation problem or a problem of me not understanding how model.predict(), or my model's output works.

The architectures I will be using for each implementation below are:

1) causal dilation CNN

2) two layers LSTM

neural network architecture diagrams here: https://imgur.com/a/cY2RWNG

For every example below the model's weights were tuned by the model training on the training data (first 80% of dataset) and attempting to achieve the lowest validation loss possible using the validation data (last 20% of dataset).

--- First Implementation ---

(unfortunately, there's an image limit on stack overflow for my current rating or whatever so I've put each implementation into its own album)

Implementation 1 - Graphs for both CNN/LSTM: Images 1-7 https://imgur.com/a/36DZCIf

In every training/validation test graph, black represents the actual data and red is the predicted data, in the forecasting predictions blue represents the predictions made and orange represents the actual close price on a longer time scale than the prediction for better scale, all forecast predictions are 30 days into the future.

Using this methodology, and displaying the actual close price against the predicted close price in every instance:

Image 1 - sliding window set up for this implementation using one and two features and a range of numbers for viewing ease

CNN:

(images 2 & 3 description in album)

Image 4 - Sliding window approach of forecasting every feature in the data, with the prediction for close price plotted against the actual close price. The timesteps start at the first row of the cutoff data.

When the first prediction is made I append the prediction to the end of this row and remove the first timestep, repeating for every future timestep I wish to predict.

I really don't even know what to say about this prediction, it's really bad...

LSTM:

(images 5 & 6 description in album)

Image 7 - Sliding window prediction: https://i.imgur.com/Ywf6xvr.png

This prediction seems to be getting the trend somewhat accurately I guess.. But the starting point is really nowhere near the last known data point which is confusing.

--- Second Implementation ---

Implementation 2 - Graphs for both CNN/LSTM: Images 1-7
https://imgur.com/a/3CAk1xc

For this attempt, I made the target prediction many timesteps into the future. With this implementation, the model takes in the current timestep(x) of features and attempts to predict the closing price at y+1, y+2,y+3 etc. There is only one prediction here -- a sequence of time steps into the future.

The same graphing and network conventions as implementation 1 had applied to this too.

Image 1 - Set up of input and target data, using a range and only one or two features for viewing ease.

CNN:

(images 2 & 3 description in album)

Image 4 - Plotting all 30 predictions made from the first row of data features after the cutoff... this is horrible, why is the start again nowhere near the last known data point? I don't understand how it can predict y+1 being so far away from the closing price of x when in every instance of its training y+1 was almost certainly extremely close to x.

LSTM:

(images 5 & 6 description in album)

Image 7 - All 30 predictions into the future made from the first row of cutoff data: Again, both all over the place and the predictions start nowhere near the last actual data point, not sure what else to add.

It's starting to appear that either my CNN implementation is poorly done or LSTM is just a better solution here. Regardless, the predictions and actual forecasting are still terrible so I'll hold my judgment on the network architecture until I get something that looks remotely like an actual forecast prediction.

--- Third Implementation ---

Implementation 3 - Graphs for both CNN/LSTM: Images 1-7
https://imgur.com/a/clcKFF8

This was the final idea I had for forecasting the future and it's essentially a combination of the first two. For this implementation, I take x-n (x, x-1, x-2, x-3) etc., which is similar to the first implementation, and set the target data to y+1, y+2, y+3, which is similar to the second implementation. My goal for predicting with this was the same strategy as the second implementation where I would predict 30 days into the future, but instead of doing so on one timestep of features, I'd do so on many timesteps into the past. I had hoped that this implementation would give the prediction enough supporting data to accurately forecast the future

Image 1 - Input data or "x" and Target data or "y" implementation and set up. I use a range of numbers again. In this example, the input data has 2 features, includes the present timestep (x) and 4 timesteps shifted backward (x-1, x-2, x-3, x-4) and the target data has 5 timesteps into the future (y+1, y+2, y+3, y+4, y+5)

CNN:

(images 2 & 3 description in album)

Image 4 - 30 predictions into the future using 101 timesteps of x

This is probably the worst result yet and that's despite the prediction having way more timesteps back of data to use.

LSTM:

(images 5 & 6 description in album)

Image 7 - 30 predictions on input data row of 101 timesteps.

This actually has some action to it I guess, but it's all over the place, doesn't start near the last actual data point and is clearly not accurate at all.

closing thoughts

I've also tried removing the target variable (close price) from the input data but it doesn't seem to change much and the past n-days of closing data should be available to a model anyway I would think.

Originally I MinMaxScaled all of my data in my pre-processing page and did not inverse_transform any of the data. The results were basically just as bad as the examples above. For the examples above I have min max scaled the prediction, validation & test datasets separately to be within the range of 0.2 - 0.8. For the actual forecasting predictions, I've inverse_transformed the data before plotting it against the actual closing price which was never transformed.

If I am doing something fundamentally wrong in the above examples I would love to know as I'm just starting out and this is my first real programming/machine learning project.

A few other things relating to this that I've come across / tried:

I've experimented briefly with using a stateful model where I reset_states() after every prediction to some moderate success.

I've read that sequence to sequence models could be useful for forecasting time series data but I'm really not sure what that system is designed to do with time series despite reading into it quite a bit and am thus not sure how to implement it or test it out.

I tried bidirectional LSTM because of one random StackOverflow post suggesting it for time series forecasting... the results were very mediocre however and it doesn't seem to make much sense to me in this situation from what I understand of how it works. I've only tried it with the first implementation above though, let me know if it's something to look more into.

Any tips/criticism at all that you could provide would be greatly appreciated, I'm really not sure how to progress from here. Thanks in advance!

答:
I have been through that,for me the sliding window approach with LSTM, NN worked like magic for small time series But on a bigger time series with data coming in on hourly basis for a few years it failed miserably.

Later on I ditched LSTM,GBTs & started implementing algos from statsmodels.tsa, ARIMA, SARIMA most of the time, I'll suggest you to read about them too. Very easy to implement no need to worry about sliding window, moving data few timestamps back, it takes care of all. Just train, tune the parameters & predict for the next timestamps.

Sometimes, I also faced issues like my time series had missing timestamps & data, then I had to impute those values, the frequency on which I trained (hourly,weekly,monthly) was different from the frequency on which I wanted to predict, then I had to bring data in right form too. I faced different frequency issue while visualising on a plot as well.

```<code>model=statsmodels.api.tsa.SARIMAX(train_df,order=(1,0,1),seasonal_order=(1,1,0,24))
model = model.fit()
</code>```

other than the data pre-processing part, imputing missing data, training on right frequency & some logic for parameters tuning, you will need to use just these two lines, your data_frame will have the index in a date format & columns will have time series data

Body:
I have been through that,for me the sliding window approach with LSTM, NN worked like magic for small time series But on a bigger time series with data coming in on hourly basis for a few years it failed miserably.

Later on I ditched LSTM,GBTs & started implementing algos from statsmodels.tsa, ARIMA, SARIMA most of the time, I'll suggest you to read about them too. Very easy to implement no need to worry about sliding window, moving data few timestamps back, it takes care of all. Just train, tune the parameters & predict for the next timestamps.

Sometimes, I also faced issues like my time series had missing timestamps & data, then I had to impute those values, the frequency on which I trained (hourly,weekly,monthly) was different from the frequency on which I wanted to predict, then I had to bring data in right form too. I faced different frequency issue while visualising on a plot as well.

model=statsmodels.api.tsa.SARIMAX(train_df,order=(1,0,1),seasonal_order=(1,1,0,24))
model = model.fit()

other than the data pre-processing part, imputing missing data, training on right frequency & some logic for parameters tuning, you will need to use just these two lines, your data_frame will have the index in a date format & columns will have time series data


问:
VPS hosting and root access
I've got rather poor knowledge of *nix virtualization capabilities and trying to clarify one thing. If one has root on host machine, does it always mean that he has root on all VMs of that host? If yes, then could there be a bogus setup where this is not true?

I'm asking cause I heard two different answers to that question from two different admins. One said that he has root to everything, another claimed that he don't and he needs my password.

Please share your experience with VPS hosting providers, do they have roots to your environment?

It's not that I'm afraid to lose the data, just want to have some insights and words to google for ;-)
Thanks everyone!

答:
You seem a little confused about how virtualization works. Consider if your question was the following:

"If I let someone sit down at my computer, do they have root access?"

A virtual machine is basically just an image that "represents" that machine. It's conceptually no different than if you had your own physical machine controlled by the hosting provider.

One exception could be dependent on the provider's setup process. Do they ask you for an initial root password to set up your VPS with? If so, they could record that, but once you log into your environment for the first time, if you change it they should no longer have any knowledge of it.

OwnerDisplayName: clorz

ContentLicense: CC BY-SA 2.5

Title: VPS hosting and root access

LastEditorDisplayName: clorz

OwnerDisplayName: Chad Birch


问:
Stretching images when using as background image
I was trying to set an image as background image for my django application. But when i set it, it is getting displayed as tiled image. ie without actually stretching the image, same image is tiled and shown 4 times. Can somebody tell me how to stretch the image and set it as a background image. I will paste my code here. I am sure some attribute must be there setting this, which i couldnt find on googling.</p>

```<code><body bgcolor=" #408080" background="/static/paper.jpg" background-size: 100%; >
</code>```

答:
You can stretch your background to 100% width and height by putting your image in an  tag and give it a z-index of -1 so it acts like a background and is behind everything else. This works in all browsers.

```<code><img src="..." />

img{
    position:absolute;
    z-index:-1;
    width:100%;
    height:100%;
}
</code>```

If you do not want to break the aspect ratio, just set either width or height and not both.

Check working example at http://jsfiddle.net/UXBRM/1/

Body:
You can stretch your background to 100% width and height by putting your image in an <img> tag and give it a z-index of -1 so it acts like a background and is behind everything else. This works in all browsers.

<img src="..." />

img{
    position:absolute;
    z-index:-1;
    width:100%;
    height:100%;
}

If you do not want to break the aspect ratio, just set either width or height and not both.

Check working example at http://jsfiddle.net/UXBRM/1/


问:
How do I use Docker environment variable in ENTRYPOINT array?
If I set an environment variable, say ENV ADDRESSEE=world, and I want to use it in the entry point script concatenated into a fixed string like:

```<code>ENTRYPOINT ["./greeting", "--message", "Hello, world!"]
</code>```

with world being the value of the environment varible, how do I do it? I tried using "Hello, $ADDRESSEE" but that doesn't seem to work, as it takes the $ADDRESSEE literally.

答:
After much pain, and great assistance from @vitr et al above, i decided to try

standard bash substitution

shell form of ENTRYPOINT (great tip from above)

and that worked.

```<code>ENV LISTEN_PORT=""

ENTRYPOINT java -cp "app:app/lib/*" hello.Application --server.port=${LISTEN_PORT:-80}
</code>```

e.g.

```<code>docker run --rm -p 8080:8080 -d --env LISTEN_PORT=8080 my-image
</code>```

and

```<code>docker run --rm -p 8080:80 -d my-image
</code>```

both set the port correctly in my container

Refs

see https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html

Body:
If I set an environment variable, say ENV ADDRESSEE=world, and I want to use it in the entry point script concatenated into a fixed string like:

ENTRYPOINT ["./greeting", "--message", "Hello, world!"]

with world being the value of the environment varible, how do I do it? I tried using "Hello, $ADDRESSEE" but that doesn't seem to work, as it takes the $ADDRESSEE literally.

Body:
After much pain, and great assistance from @vitr et al above, i decided to try

standard bash substitution

shell form of ENTRYPOINT (great tip from above)

and that worked.

ENV LISTEN_PORT=""

ENTRYPOINT java -cp "app:app/lib/*" hello.Application --server.port=${LISTEN_PORT:-80}

e.g.

docker run --rm -p 8080:8080 -d --env LISTEN_PORT=8080 my-image

and

docker run --rm -p 8080:80 -d my-image

both set the port correctly in my container

Refs

see https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html


问:
First time return undefined and second the correct result, how can i fix it?
i have an issue with call on a webservice by using Angular 7. The call is made on this way on my service :

```<code>getLogin(usr: String, pwd: String) {
    return this.http.post("the url of webservice", { username: usr, password: pwd
    });
}
</code>```

and on my component :

```<code> credenzialiConfronto() {
this.cred.getLogin(this.loginForm.get("username").value, this.loginForm.get("psw").value).subscribe((res => {
  this.User = res;
}));

console.log(this.User);
</code>```

why it returns undefined the first time and the second time not?

EDIT :

on my component i try this now but not work :

https://imgur.com/a/LJ5o4HW

and on my service :

https://imgur.com/gUe3sh5

答:
I believe you caused a race condition. The first time you log the user, it has not yet been returned by the service. Instead, you can log it like:

```<code>credenzialiConfronto() {
  this.cred.getLogin(this.loginForm.get("username").value, this.loginForm.get("psw").value)
  .pipe(
    tap(user => console.log(user))
  )
  .subscribe((res => {
    this.User = res;
}));
</code>```

With this change, you only log the user, when the getLogin call has returned.

Body:
i have an issue with call on a webservice by using Angular 7. The call is made on this way on my service :

getLogin(usr: String, pwd: String) {
    return this.http.post("the url of webservice", { username: usr, password: pwd
    });
}

and on my component :

 credenzialiConfronto() {
this.cred.getLogin(this.loginForm.get("username").value, this.loginForm.get("psw").value).subscribe((res => {
  this.User = res;
}));

console.log(this.User);

why it returns undefined the first time and the second time not?

EDIT :

on my component i try this now but not work :

https://imgur.com/a/LJ5o4HW

and on my service :

https://imgur.com/gUe3sh5

Body:
I believe you caused a race condition. The first time you log the user, it has not yet been returned by the service. Instead, you can log it like:

credenzialiConfronto() {
  this.cred.getLogin(this.loginForm.get("username").value, this.loginForm.get("psw").value)
  .pipe(
    tap(user => console.log(user))
  )
  .subscribe((res => {
    this.User = res;
}));

With this change, you only log the user, when the getLogin call has returned.


问:
No longer able to use bundleReleaseAar in MavenPublication
After upgrading Gradle to 5.1.1, I found that I'm unable to add bundleReleaseAar as an artifact to my MavenPublication. Here's the relevant snippet of my build.gradle:

```<code>apply plugin: 'maven-publish'

publishing {
    publications {
        aar(MavenPublication) {
            groupId libraryGroupId
            version libraryVersion
            artifactId libraryArtifactId

            artifact bundleReleaseAar
            //artifact sourcesJar
            //artifact packageJavadoc
        }
    }
}
</code>```

This fails with:

Could not get unknown property 'bundleReleaseAar' for object of type org.gradle.api.publish.maven.internal.publication.DefaultMavenPublication.

However, I am able to see that bundleReleaseAar does indeed exist when I run ./gradlew tasks, and I can execute that task just fine.

What is preventing it from being used as an artifact in my deployment now?

答:
I solved it by calling the artifact function into the afterEvaluate closure, the issue is that the artifact function does not handle all the configuration lazily

```<code>publishing {
   publications {
      aar(MavenPublication) {
        groupId libraryGroupId
        version libraryVersion
        artifactId libraryArtifactId
        afterEvaluate {
           artifact bundleReleaseAar
           //artifact sourcesJar
           //artifact packageJavadoc
        }
     }
   }
}
</code>```

Reference https://github.com/moberwasserlechner/capacitor-oauth2/issues/10

Body:
After upgrading Gradle to 5.1.1, I found that I'm unable to add bundleReleaseAar as an artifact to my MavenPublication. Here's the relevant snippet of my build.gradle:

apply plugin: 'maven-publish'

publishing {
    publications {
        aar(MavenPublication) {
            groupId libraryGroupId
            version libraryVersion
            artifactId libraryArtifactId

            artifact bundleReleaseAar
            //artifact sourcesJar
            //artifact packageJavadoc
        }
    }
}

This fails with:

Could not get unknown property 'bundleReleaseAar' for object of type org.gradle.api.publish.maven.internal.publication.DefaultMavenPublication.

However, I am able to see that bundleReleaseAar does indeed exist when I run ./gradlew tasks, and I can execute that task just fine.

What is preventing it from being used as an artifact in my deployment now?

Body:
I solved it by calling the artifact function into the afterEvaluate closure, the issue is that the artifact function does not handle all the configuration lazily

publishing {
   publications {
      aar(MavenPublication) {
        groupId libraryGroupId
        version libraryVersion
        artifactId libraryArtifactId
        afterEvaluate {
           artifact bundleReleaseAar
           //artifact sourcesJar
           //artifact packageJavadoc
        }
     }
   }
}

Reference https://github.com/moberwasserlechner/capacitor-oauth2/issues/10