问:
Spiky kubernetes HPA with metric number of pubsub unacked messsages
Currently we have a pipeline of data streaming: api call -> google pub/sub -> BigQuery. The number of api call will depend on the traffic on the website.

We create a kubernetes deployment (in GKE) for ingesting data from pub/sub to BigQuery. This deployment have a horizontal pod autoscaler (HPA) with with metricName: pubsub.googleapis.com|subscription|num_undelivered_messages and targetValue: "5000". This structure able to autoscale when the traffic have a sudden increase. However, it will cause a spiky scaling.

What I meant by spiky is as follows:

The number of unacked messages will go up more than the target value

The autoscaler will increase the number of pods

Since the number of unacked will slowly decrease, but since it is still above target value the autoscaler will still increase the number of pods --> this happen until we hit the max number of pods in the autoscaler

The number of unacked will decrease until it goes below target and it will stay very low

The autoscaler will reduce the number of pods to the minimum number of pods

The number of unacked messages will increase again and will go similar situation with (1) and it will go into a loop/cycle of spikes

Here are the chart when it goes spiky (the traffic is going up but it is stable and non-spiky):
The spiky number of unacknowledged message in pub/sub

We set an alarm in stackdriver if the number of unacknowledged message is more than 20k, and in this situation it will always triggered frequently.

Is there a way so that the HPA become more stable (non-spiky) in this case?

Any comment, suggestion, or answer is well appreciated.

Thanks!

答:
I've been dealing with the same behavior. What I ended up doing is smoothing the num_undelivered_messages using a moving average. I set up a k8s cron that publishes the average of the last 20 mins of time series data to a custom metric every minute. Then configured the HPA to respond to the custom metric.

This worked pretty good but not perfect. I observed that as soon as the average converges on the actual value, the HPA will scale the service down too low. So I ended up just adding a constant, so the custom metric is just average + constant. I found for my specific case a value of 25,000 worked well.

With this, and after dialing in the targetAverageValue, the autoscaling has been very stable.

I'm not sure if this is due to a defect or just the nature of the num_undelivered_messages metric at very high loads.

Edit:
I used the stackdriver/monitoring golang packages. There is a straightforward way to aggregate the time series data; see here under 'Aggregating data' https://cloud.google.com/monitoring/custom-metrics/reading-metrics

https://cloud.google.com/monitoring/custom-metrics/creating-metrics


来源: stackexchange

问:
Is there any scenario where using multithreading on a single core CPU be beneficial?
I know that using multithreading in a single core CPU is possible. But can somebody help me out with a situation or a scenario where it might be useful. I was asked this question in an interview round.</p>

答:
Even a machine with single core CPU has I/O devices: network card, hard disks, keyboard, mouse ets. Typical thread mixes computations with I/O operations. When a thread waits for data to be read from devices, it frees CPU, and it can be used by another thread if that another thread exists, which means that multithreading is used.

And when the time spent on I/O operations is negligible, multithreading still can be useful - it can make program more simple, if the task can be naturally parallelized.

ContentLicense: CC BY-SA 4.0


问:
Doesn't see a bean using Autowired annotation, nothing helps
I'm trying to autowire the Service in my Spring MVC app and it always fails! Tried everything from every question on the Internet but I couldn't find the answer. The problem is that Spring actually can't autowire field and says there is no such bean,

Tried everything, changing the code, configuration, etc. Maybe for now everything in my project is too messed up and I can't find the bug.

```<code>@Controller
public class ViewController {

    @Autowired
    private IUserService userService;

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
}
</code>```

```<code>@Component
@Service("userService")
public class UserServiceImpl implements IUserService {

    private static final SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").
            addAnnotatedClass(User.class).addAnnotatedClass(Restaurant.class).
            buildSessionFactory();

    public UserServiceImpl() {
    }
}
</code>```

dispatcher-servlet.xml

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

    <!-- Step 3: Add support for component scanning -->
    <context:component-scan base-package="com.springmvcdemo.Controller" />

    <!-- Step 4: Add support for conversion, formatting and validation support -->
    <mvc:annotation-driven/>

    <!-- Step 5: Define Spring MVC view resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>
</code>```

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <display-name>spring-mvc-demo</display-name>

    <absolute-ordering />
    <!-- Step 1: Configure Spring MVC Dispatcher Servlet -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

applicationContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config />
    <context:component-scan base-package="com.springmvcdemo.Services" />
</beans>
</code>```

```<code>Error creating bean with name 'viewController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.springmvcdemo.Services.IUserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code>```

答:
So the problem is that the SessionFactory was being constructed in a static field of the service.

The class could be found, but there was some error creating the session factory which is why the error message contains "Instantiation of bean failed".

Moving the session factory to be managed by Spring and then injecting it was the way to go.

Body:
I'm trying to autowire the Service in my Spring MVC app and it always fails! Tried everything from every question on the Internet but I couldn't find the answer. The problem is that Spring actually can't autowire field and says there is no such bean,

Tried everything, changing the code, configuration, etc. Maybe for now everything in my project is too messed up and I can't find the bug.

@Controller
public class ViewController {

    @Autowired
    private IUserService userService;

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
}

@Component
@Service("userService")
public class UserServiceImpl implements IUserService {

    private static final SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").
            addAnnotatedClass(User.class).addAnnotatedClass(Restaurant.class).
            buildSessionFactory();

    public UserServiceImpl() {
    }
}

dispatcher-servlet.xml

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

    <context:component-scan base-package="com.springmvcdemo.Controller" />

    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <display-name>spring-mvc-demo</display-name>

    <absolute-ordering />

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config />
    <context:component-scan base-package="com.springmvcdemo.Services" />
</beans>

Error creating bean with name 'viewController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.springmvcdemo.Services.IUserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}


问:
how to use reportlab with google app engine
I am unable to import reportlab properly under google app engine. According to the following guide (and several other places on the web):

"All you have to do is download it and copy the 'reportab' directory into the root directory of your app. "

When I do so (I download the reportlab-3.0.zip from here) and extract it into the root directory of my application, as I try to import reportlab using following lines:

```<code>from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
</code>```

I get an import error

```<code>ImportError: No module named reportlab.pdfgen
</code>```

I tried googling but to no avail. Any help on this would be greatly appreciated as I am not sure what else I could try. Many thanks!

One other thing I tried was copying what's in the src directory of the downloaded zip under the root directory of my application but that didn't work either. The error I get using this is:

```<code>ImportError: Cannot re-init internal module __main__
</code>```

Seems version 2.7 imports okay, only issues with 3.0

答:
You need to move to the lib's parent directory. Then you can install reportlab using this command:</p>

```<code>pip install -t lib reportlab
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am unable to import reportlab properly under google app engine. According to the following guide (and several other places on the web):

"All you have to do is download it and copy the 'reportab' directory into the root directory of your app. "

When I do so (I download the reportlab-3.0.zip from here) and extract it into the root directory of my application, as I try to import reportlab using following lines:

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4

I get an import error

ImportError: No module named reportlab.pdfgen

I tried googling but to no avail. Any help on this would be greatly appreciated as I am not sure what else I could try. Many thanks!

One other thing I tried was copying what's in the src directory of the downloaded zip under the root directory of my application but that didn't work either. The error I get using this is:

ImportError: Cannot re-init internal module __main__

Seems version 2.7 imports okay, only issues with 3.0

Body:
You need to move to the lib's parent directory. Then you can install reportlab using this command:

pip install -t lib reportlab


问:
How to pass a column argument in a dplyr function in select?
I have a dataframe that needs to be summarized by column B into one dataframe. I also need to summarize this dataframe by column A into another dataframe. For context's sake, column B is a subcolumn of column A in hierarchy. I also only need columns C:E, so I decided that dplyr would be the most helpful.

```<code>A  |  B  |  C  |  D  |  E  |  F |  G
-------------------------------------
1    1A     3     4     5     3    2
1    1B     4     4     4     4    3
2    2A     2     2     2     2    2
...
</code>```

My team decided that a function would be the most efficient way to write this in order to achieve cleaner code. If I wanted to summarize the dataframe by column A, I know I would write the script to be something such as this:

```<code>df %>%
select(A, C, D, E) %>%
group_by(A) %>%
summarise(C = sum(C), D = sum(D), E = sum(E)
</code>```

and B such as this:

```<code>df %>%
select(B, C, D, E) %>%
group_by(B) %>%
summarise(C = sum(C), D = sum(D), E = sum(E)
</code>```

I am struggling to translate this into a function that works for either scenario. Here is what I have so far:

```<code>slicedata <- function(df, column_name){

df %>%
select(column_name, C, D, E) %>%
group_by(column_name) %>%
summarise(C = sum(C), D = sum(D), E = sum(E)

}
</code>```

But when I pass column B as an argument in that function, this is what I get:

```<code>slicedata(df, B)
Error in .f(.x[[i]], ...) : object 'B' not found
</code>```

Basically: I am trying to write a function for this dataframe that allows me to aggregate the integer columns by whichever column I pass as an argument. I do not understand why this error is showing up, however.

答:
We can use enquo to convert it to a quosure and then evaluate with !!

```<code>slicedata <- function(df, column_name){
  column_name = enquo(column_name)
  df %>%
    select(!!column_name, C, D, E) %>%
    group_by(!!column_name) %>%
    summarise(C = sum(C), D = sum(D), E = sum(E)

  }

slicedata(df, B)
</code>```

Body:
I have a dataframe that needs to be summarized by column B into one dataframe. I also need to summarize this dataframe by column A into another dataframe. For context's sake, column B is a subcolumn of column A in hierarchy. I also only need columns C:E, so I decided that dplyr would be the most helpful.

A  |  B  |  C  |  D  |  E  |  F |  G
-------------------------------------
1    1A     3     4     5     3    2
1    1B     4     4     4     4    3
2    2A     2     2     2     2    2
...

My team decided that a function would be the most efficient way to write this in order to achieve cleaner code. If I wanted to summarize the dataframe by column A, I know I would write the script to be something such as this:

df %>%
select(A, C, D, E) %>%
group_by(A) %>%
summarise(C = sum(C), D = sum(D), E = sum(E)

and B such as this:

df %>%
select(B, C, D, E) %>%
group_by(B) %>%
summarise(C = sum(C), D = sum(D), E = sum(E)

I am struggling to translate this into a function that works for either scenario. Here is what I have so far:

slicedata <- function(df, column_name){

df %>%
select(column_name, C, D, E) %>%
group_by(column_name) %>%
summarise(C = sum(C), D = sum(D), E = sum(E)

}

But when I pass column B as an argument in that function, this is what I get:

slicedata(df, B)
Error in .f(.x[[i]], ...) : object 'B' not found

Basically: I am trying to write a function for this dataframe that allows me to aggregate the integer columns by whichever column I pass as an argument. I do not understand why this error is showing up, however.

Body:
We can use enquo to convert it to a quosure and then evaluate with !!

slicedata <- function(df, column_name){
  column_name = enquo(column_name)
  df %>%
    select(!!column_name, C, D, E) %>%
    group_by(!!column_name) %>%
    summarise(C = sum(C), D = sum(D), E = sum(E)

  }

slicedata(df, B)


问:
How to backup Symmetric Key in SQL Server?
I use the next code to create SQL Encryption keys

```<code>CREATE MASTER KEY ENCRYPTION BY PASSWORD = '<Pass>'
CREATE CERTIFICATE MyEncryptCert WITH SUBJECT = 'Descryption', EXPIRY_DATE = '2115-1-1'
CREATE SYMMETRIC KEY MySymmetricKey WITH ALGORITHM = AES_256 ENCRYPTION BY CERTIFICATE MyEncryptCert
</code>```

How I encrypt data

```<code>OPEN SYMMETRIC KEY MySymmetricKey DECRYPTION BY CERTIFICATE MyEncryptCert
SET @Result = ENCRYPTBYKEY(KEY_GUID('MySymmetricKey'), '<String to encrypt>')
CLOSE SYMMETRIC KEY MySymmetricKey
</code>```

I am able to backup Database Master Key and Certificate.

```<code>BACKUP MASTER KEY TO FILE = 'c:\temp\key' ENCRYPTION BY PASSWORD = '<Pass>';
BACKUP CERTIFICATE MyEncryptCert TO FILE = 'c:\temp\cert' WITH PRIVATE KEY(ENCRYPTION BY PASSWORD='<Pass>', FILE='C:\temp\cert.pvk')
</code>```

But I can not backup Symmetric Key. Without it I can not decrypt the encrypted data if I move the encrypted table to another Database.

Is there any solutions?

P.S. I tried the next code, but seems it is not safe to me, because if you know KEY_SOURCE and IDENTITY_VALUE you actually do not need original Database Master Key and Certificate to decrypt the data

```<code>CREATE SYMMETRIC KEY MySymmetricKey WITH KEY_SOURCE = '<Pass1>', ALGORITHM = AES_256, IDENTITY_VALUE = '<Pass2>' ENCRYPTION BY CERTIFICATE MyEncryptCert
</code>```

答:
You can't.

As noted in another answer, it's possible to recreate the same symmetric key using the same parameters, but this does not work between different versions of SQL Server.

Body:
I use the next code to create SQL Encryption keys

CREATE MASTER KEY ENCRYPTION BY PASSWORD = '<Pass>'
CREATE CERTIFICATE MyEncryptCert WITH SUBJECT = 'Descryption', EXPIRY_DATE = '2115-1-1'
CREATE SYMMETRIC KEY MySymmetricKey WITH ALGORITHM = AES_256 ENCRYPTION BY CERTIFICATE MyEncryptCert

How I encrypt data

OPEN SYMMETRIC KEY MySymmetricKey DECRYPTION BY CERTIFICATE MyEncryptCert
SET @Result = ENCRYPTBYKEY(KEY_GUID('MySymmetricKey'), '<String to encrypt>')
CLOSE SYMMETRIC KEY MySymmetricKey

I am able to backup Database Master Key and Certificate.

BACKUP MASTER KEY TO FILE = 'c:\temp\key' ENCRYPTION BY PASSWORD = '<Pass>';
BACKUP CERTIFICATE MyEncryptCert TO FILE = 'c:\temp\cert' WITH PRIVATE KEY(ENCRYPTION BY PASSWORD='<Pass>', FILE='C:\temp\cert.pvk')

But I can not backup Symmetric Key. Without it I can not decrypt the encrypted data if I move the encrypted table to another Database.

Is there any solutions?

P.S. I tried the next code, but seems it is not safe to me, because if you know KEY_SOURCE and IDENTITY_VALUE you actually do not need original Database Master Key and Certificate to decrypt the data

CREATE SYMMETRIC KEY MySymmetricKey WITH KEY_SOURCE = '<Pass1>', ALGORITHM = AES_256, IDENTITY_VALUE = '<Pass2>' ENCRYPTION BY CERTIFICATE MyEncryptCert


问:
Intercept Angular URL with PHP first before loading webpage
We currently have a full Angular project running in a sub-dir on our server and a physical "device" using a hardcoded URL to send a user to that page.

I'm looking for some kind of way to "intercept" the request via a PHP script first to (for example, not the real purpose) see if the requested "ID" param for that browser page has enabled the option to view the browser page or if it has been configured by the user to return a 406 HTTP response (for example).

```<code>Currently:
- ..com/app/routing-view?id=1234 => Angular view -> fetch info

Idea:
- ..com/app/routing-view?id=1234 => PHP-script -> isValid => forward to angular and do a normal 'webview' -> fetch info
- ..com/app/routing-view?id=2889 => PHP-script -> notValid => HTTP code

</code>```

I thought about having a .htaccess "intercept" the url and forward it to a .php file. Do the magic and checks there, and then forward the browser to the original url, but to "bypass" the previous interceptor.

It's about that last part that I'm currently having issues. Because it's Angular and it is using paths, I can't just say "okay, redirect to index.html instead of index.php" because it would need to be something like ..com/app/routing-view?id=1234 (and the index.html is located in the /app directory.

I don't want to add PHP code to the original Angular-index file if that could be avoided.

Am I looking at this right or would there be a different, more efficient way to tackle this?

The reason for all this is that I want to (for example) return a different HTTP code or different headers to the device instead of a 200 html header response even if the ID turned out to be disabled or something like that.

答:
Got it to work via a simple .htaccess, a parameter and an "interceptor" script. Quite simple and basic really, not sure why my brain didn't go this route before posting my question.

Added the .htaccess to the root of the Angular application with the following code.

```<code>RewriteEngine On

# Check if the request has been intercepted before (via URL parameter)
RewriteCond %{QUERY_STRING} !(^|&)intercepted=true

# .. If not, rewrite the page to use the interceptor script (only if it matches the route).
RewriteRule ^my-route dir-of-script/extra/interceptor.php?url=https://%{HTTP_HOST}%{REQUEST_URI}?%{QUERY_STRING} [L,QSA]

# Other stuff for rewriting the Angular routes etc
...

</code>```

Added a /dir-of-script/extra/interceptor.php like-script that parses the URL from the GET parameter, fetches the info, does the checks and depending on the result, returns the output or redirects the page and let it through.

This adds a ..&intercepted=true parameter to the original URL so that the .htaccess doesn't intercept it again.

This seems to be working like a charm (for my situation). The only "downside" is that this counts as a redirect and not just a rewrite when it was allowed to go through. Will look further into it, to maybe let the PHP script "serve" the Angular content instead of redirecting to it.

Body:
We currently have a full Angular project running in a sub-dir on our server and a physical "device" using a hardcoded URL to send a user to that page.

I'm looking for some kind of way to "intercept" the request via a PHP script first to (for example, not the real purpose) see if the requested "ID" param for that browser page has enabled the option to view the browser page or if it has been configured by the user to return a 406 HTTP response (for example).

Currently:
- ..com/app/routing-view?id=1234 => Angular view -> fetch info

Idea:
- ..com/app/routing-view?id=1234 => PHP-script -> isValid => forward to angular and do a normal 'webview' -> fetch info
- ..com/app/routing-view?id=2889 => PHP-script -> notValid => HTTP code

I thought about having a .htaccess "intercept" the url and forward it to a .php file. Do the magic and checks there, and then forward the browser to the original url, but to "bypass" the previous interceptor.

It's about that last part that I'm currently having issues. Because it's Angular and it is using paths, I can't just say "okay, redirect to index.html instead of index.php" because it would need to be something like ..com/app/routing-view?id=1234 (and the index.html is located in the /app directory.

I don't want to add PHP code to the original Angular-index file if that could be avoided.

Am I looking at this right or would there be a different, more efficient way to tackle this?

The reason for all this is that I want to (for example) return a different HTTP code or different headers to the device instead of a 200 html header response even if the ID turned out to be disabled or something like that.

Body:
Got it to work via a simple .htaccess, a parameter and an "interceptor" script. Quite simple and basic really, not sure why my brain didn't go this route before posting my question.

Added the .htaccess to the root of the Angular application with the following code.

RewriteEngine On

# Check if the request has been intercepted before (via URL parameter)
RewriteCond %{QUERY_STRING} !(^|&)intercepted=true

# .. If not, rewrite the page to use the interceptor script (only if it matches the route).
RewriteRule ^my-route dir-of-script/extra/interceptor.php?url=https://%{HTTP_HOST}%{REQUEST_URI}?%{QUERY_STRING} [L,QSA]

# Other stuff for rewriting the Angular routes etc
...

Added a /dir-of-script/extra/interceptor.php like-script that parses the URL from the GET parameter, fetches the info, does the checks and depending on the result, returns the output or redirects the page and let it through.

This adds a ..&intercepted=true parameter to the original URL so that the .htaccess doesn't intercept it again.

This seems to be working like a charm (for my situation). The only "downside" is that this counts as a redirect and not just a rewrite when it was allowed to go through. Will look further into it, to maybe let the PHP script "serve" the Angular content instead of redirecting to it.


问:
palindrome with a stack using linked lists does not return the correct answer
I have been implementing a Stack by using a linked list. The implementation is the following:

```<code>public class Node {
    public Object e;
    Node next;
    public Node(Object e){
        this.e=e;
    }
}

public class Stack {
    Nodo last, first;
    int count;
    public void push(Object n){
        Nodo temp=new Nodo(n);
        temp.next=last;
        last=temp;
        if (first==null){
            first=temp;
        }
        count++;
    }
    public boolean isEmpty(){
        if (count==0) return true;
        else return false;
    }
    public Object pop(){
        Object obj=null;
        if (isEmpty()){
            return -1;
        }
        else{
            obj=last.e;
            last=last.next;
        }
        count--;
        return obj;
    }
    public void print(){
        Nodo current=last;
        while (current!=null){
            System.out.println(current.e);
            current=current.next;
        }
    }
public boolean palindrome(){
        Stack cadT1=new Stack();
        Stack cadT2=new Stack();
        cadT1=this;
        //System.out.println(this.isEmpty());
        while (this.isEmpty()!=true){
            cadT2.push(this.pop());
        }
        cadT1.print();
        while (cadT1.isEmpty()!=true){
            /*if (!(cadT1.pop().equals(cadT2.pop()))){
                return false;
            }*/
            System.out.println(cadT1.pop()+" "+cadT2.pop());
        }
        return true;
    }
</code>```

I have a problem with the implementation of the palindrome function, in which I am also using stacks. The problem that I have is that it always returns the value of true. I have commented the portion of the code that currently is not working. While analyzing my code I found that when I do the following assignment:

```<code>cadT1=this;
</code>```

The cadT1 variable is still empty. I have tested this by putting the following line in the while of the palindrome function:

```<code>System.out.println(cadT1.pop()+" "+cadT2.pop());
</code>```

and I have seen that my code does not execute that line, that is because the condition in the while loop:

```<code>while (cadT1.isEmpty()!=true){
</code>```

is always set to false.
The running code in my main class is the following:

```<code> Stack word=new Stack();
    word.push('a');
    word.push('s');
    word.push('d');
    word.push('f');
    System.out.println(word.palindrome());
</code>```

What am I doing wrong? Thanks

答:
That is because you have already popped all the elements from the current stack with this

```<code>cadT2.push(this.pop());
</code>```

Now, when you call cadT1.print(), it won't print anything (cadT1 is the reference to the current stack). Hence, cadT1.isEmpty() will be true.

What you can do is to iterate the linked list and build the second stack rather than popping the elements from the current stack to build the second stack (If you pop, you won't have any elements in the current stack to compare against).

Body:
I have been implementing a Stack by using a linked list. The implementation is the following:

public class Node {
    public Object e;
    Node next;
    public Node(Object e){
        this.e=e;
    }
}

public class Stack {
    Nodo last, first;
    int count;
    public void push(Object n){
        Nodo temp=new Nodo(n);
        temp.next=last;
        last=temp;
        if (first==null){
            first=temp;
        }
        count++;
    }
    public boolean isEmpty(){
        if (count==0) return true;
        else return false;
    }
    public Object pop(){
        Object obj=null;
        if (isEmpty()){
            return -1;
        }
        else{
            obj=last.e;
            last=last.next;
        }
        count--;
        return obj;
    }
    public void print(){
        Nodo current=last;
        while (current!=null){
            System.out.println(current.e);
            current=current.next;
        }
    }
public boolean palindrome(){
        Stack cadT1=new Stack();
        Stack cadT2=new Stack();
        cadT1=this;
        //System.out.println(this.isEmpty());
        while (this.isEmpty()!=true){
            cadT2.push(this.pop());
        }
        cadT1.print();
        while (cadT1.isEmpty()!=true){
            /*if (!(cadT1.pop().equals(cadT2.pop()))){
                return false;
            }*/
            System.out.println(cadT1.pop()+" "+cadT2.pop());
        }
        return true;
    }

I have a problem with the implementation of the palindrome function, in which I am also using stacks. The problem that I have is that it always returns the value of true. I have commented the portion of the code that currently is not working. While analyzing my code I found that when I do the following assignment:

cadT1=this;

The cadT1 variable is still empty. I have tested this by putting the following line in the while of the palindrome function:

System.out.println(cadT1.pop()+" "+cadT2.pop());

and I have seen that my code does not execute that line, that is because the condition in the while loop:

while (cadT1.isEmpty()!=true){

is always set to false.
The running code in my main class is the following:

 Stack word=new Stack();
    word.push('a');
    word.push('s');
    word.push('d');
    word.push('f');
    System.out.println(word.palindrome());

What am I doing wrong? Thanks

Body:
That is because you have already popped all the elements from the current stack with this

cadT2.push(this.pop());

Now, when you call cadT1.print(), it won't print anything (cadT1 is the reference to the current stack). Hence, cadT1.isEmpty() will be true.

What you can do is to iterate the linked list and build the second stack rather than popping the elements from the current stack to build the second stack (If you pop, you won't have any elements in the current stack to compare against).


问:
How to resample pandas dataframe to model an average week?
I have a dataframe of number of messages and the time period they were sent in (increments of 10 minutes). Here's a snippet:

```<code>+---------------------+--------------+
|      UnixTime       | Num messages |
+---------------------+--------------+
| 2019-02-01 00:00:00 |           54 |
| 2019-02-01 00:10:00 |           23 |
| 2019-02-01 00:20:00 |           36 |
+---------------------+--------------+
</code>```

This dataframe has a year's worth of increment timestamps and the number of messages in that period. How can I model a mean/median week using the entire dataframe and as the day of week as a reference.

```<code>+-----------------+-------------------------+
| UnixTime (Mean) | Mean number of messages |
+-----------------+-------------------------+
| Friday 00:00:00 | 56.3                    |
| Friday 00:10:00 | 25.5                    |
| Friday 00:20:00 | 30.4                    |
+-----------------+-------------------------+
</code>```

So the output dataframe should model an average week from Monday-Sunday for the year, with the number of messages averaged over the year for that time period and day.

I know I can get the day of the week by df["Day Of Week"] = df['UnixTime'].dt.day_name() but how can I model the average so that each Monday of the year between 09:00 - 09:10 is treated as the same group for example.

答:
We can have a new column "weekNum" to label each row as part of the Nth week of the year. We can do this with floor division on the numeric values of the days.

```<code>df["weekNum"] = int(df["UnixTime"].dt.day//7)
</code>```

We can then groupby:

```<code>df.groupby("weekNum").mean()
df.groupby("Day of week").mean()
</code>```

EDIT:

To get each 10 second interval now that I understand your question better...we can use .strftime and format our times to day name %A hour, minute, second %H%M%S and group by that.

```<code>df["dayTime"] = df.UnixTime.dt.strftime("%A%H%M%S")
df.groupby("dayTime").mean()
</code>```

Body:
I have a dataframe of number of messages and the time period they were sent in (increments of 10 minutes). Here's a snippet:

+---------------------+--------------+
|      UnixTime       | Num messages |
+---------------------+--------------+
| 2019-02-01 00:00:00 |           54 |
| 2019-02-01 00:10:00 |           23 |
| 2019-02-01 00:20:00 |           36 |
+---------------------+--------------+

This dataframe has a year's worth of increment timestamps and the number of messages in that period. How can I model a mean/median week using the entire dataframe and as the day of week as a reference.

+-----------------+-------------------------+
| UnixTime (Mean) | Mean number of messages |
+-----------------+-------------------------+
| Friday 00:00:00 | 56.3                    |
| Friday 00:10:00 | 25.5                    |
| Friday 00:20:00 | 30.4                    |
+-----------------+-------------------------+

So the output dataframe should model an average week from Monday-Sunday for the year, with the number of messages averaged over the year for that time period and day.

I know I can get the day of the week by df["Day Of Week"] = df['UnixTime'].dt.day_name() but how can I model the average so that each Monday of the year between 09:00 - 09:10 is treated as the same group for example.

Body:
We can have a new column "weekNum" to label each row as part of the Nth week of the year. We can do this with floor division on the numeric values of the days.

df["weekNum"] = int(df["UnixTime"].dt.day//7)

We can then groupby:

df.groupby("weekNum").mean()
df.groupby("Day of week").mean()

EDIT:

To get each 10 second interval now that I understand your question better...we can use .strftime and format our times to day name %A hour, minute, second %H%M%S and group by that.

df["dayTime"] = df.UnixTime.dt.strftime("%A%H%M%S")
df.groupby("dayTime").mean()


问:
Vue2-leaflet map not showing properly in BoostrapVue modal
Here's my problem - a Vue2 leaflet map does not render correctly in BootstrapVue modal.

Here's what it looks like visually (it should show just the ocean)

<template>

        <l-map :center="center" :zoom="13" ref="mymap">
          <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
          <l-marker :lat-lng="center"></l-marker>
        </l-map>

      <template slot="modal-footer">
        Delete
      </template>

</template>

```

As you can see there aren't any CSS rules that could make the map spill outside the modal as it does. Which is weird.

I'm kinda asking this question to answer it myself as I couldn't find a solution before.

答:
There were 3 issues because of which this was happening.

1. First - I forgot to load the leaflet css into main.js - this is why the leaflet map was somehow outside the modal.

//src/main.js
import '@babel/polyfill';
import Vue from 'vue';
import './plugins/bootstrap-vue';
import App from './App.vue';
import router from './router';
import store from './store';
//above imports not important to this answer

import 'leaflet/dist/leaflet.css'; //<--------------add this line

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app');
```
<hr />
<p><strong>2.</strong> Now the map may disappear. Set a width and height on the <code>l-map</code> component's container. I used a class but you can use style="" etc.</p>
<pre class="lang-html prettyprint-override"><code><div class="foobar1"> <!-- <--- Add a class on l-map's container -->
  <l-map :center="center" :zoom="13">
    <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
    <l-marker :lat-lng="center"></l-marker>
  </l-map>
</div>
</code>```

```
<hr />
<p><strong>3.</strong> Now your map will render within the modal but if you move the map's view, you'll see that leaflet does not download the map's squares in time.
You will see something like this:</p>
<p><img src="https://i.stack.imgur.com/P0uB1.png" alt="modal after fixing css but without invalidateSize() fix" /></p>
<p>To fix this:</p>
<ul>
<li><p>create an event handler on <code>b-modal</code> for the <code>@shown</code> event.</p>
<pre class="lang-html prettyprint-override"><code> <b-modal
   @shown="modalShown"

   @hidden="$emit('clear')"
   size="lg"
   :visible="visible"
   title="Event details"
 >
</code>```

I called mine modalShown.

Then, add a ref attribute to your l-map. I called mine mymap.

<l-map :center="center" :zoom="13" ref="mymap">
  <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
  <l-marker :lat-lng="center"></l-marker>
</l-map>
```
</li>
<li><p>Then, create a <code>modalShown</code> method in the Vue methods for your view/component and call <code>invalidateSize()</code> inside.</p>
<pre class="lang-js prettyprint-override"><code>export default {
  data() {
   //some data here
  }

  methods: {
     modalShown() {
      setTimeout(() => {
        //mapObject is a property that is part of leaflet
        this.$refs.mymap.mapObject.invalidateSize();
      }, 100);
    }
  }
}
</code>```

Now everything should be fine:

map should not spill outside the modal

map should be visible (duh)

map squares should be downloaded when within map body

Here's my full code, it contains some stuff specific to my app but overall it contains all of the code snippets above.

Body:
Here's my problem - a Vue2 leaflet map does not render correctly in BootstrapVue modal.

Here's what it looks like visually (it should show just the ocean)

<template>

        <l-map :center="center" :zoom="13" ref="mymap">
          <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
          <l-marker :lat-lng="center"></l-marker>
        </l-map>

      <template slot="modal-footer">
        Delete
      </template>

</template>

As you can see there aren't any CSS rules that could make the map spill outside the modal as it does. Which is weird.

I'm kinda asking this question to answer it myself as I couldn't find a solution before.

Body:
There were 3 issues because of which this was happening.

1. First - I forgot to load the leaflet css into main.js - this is why the leaflet map was somehow outside the modal.

//src/main.js
import '@babel/polyfill';
import Vue from 'vue';
import './plugins/bootstrap-vue';
import App from './App.vue';
import router from './router';
import store from './store';
//above imports not important to this answer

import 'leaflet/dist/leaflet.css'; //<--------------add this line

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app');

2. Now the map may disappear. Set a width and height on the l-map component's container. I used a class but you can use style="" etc.

<div class="foobar1"> <!-- <--- Add a class on l-map's container -->
  <l-map :center="center" :zoom="13">
    <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
    <l-marker :lat-lng="center"></l-marker>
  </l-map>
</div>

<style lang="scss">
  .foobar1 { /* <--- class we added above */
    width: 100%;
    height: 400px;
  }
</style>

3. Now your map will render within the modal but if you move the map's view, you'll see that leaflet does not download the map's squares in time.
You will see something like this:

To fix this:

create an event handler on b-modal for the @shown event.

 <b-modal
   @shown="modalShown"

   @hidden="$emit('clear')"
   size="lg"
   :visible="visible"
   title="Event details"
 >

I called mine modalShown.

Then, add a ref attribute to your l-map. I called mine mymap.

<l-map :center="center" :zoom="13" ref="mymap"> <!-- ref attribute added to l-map -->
  <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
  <l-marker :lat-lng="center"></l-marker>
</l-map>

Then, create a modalShown method in the Vue methods for your view/component and call invalidateSize() inside.

export default {
  data() {
   //some data here
  }

  methods: {
     modalShown() {
      setTimeout(() => {
        //mapObject is a property that is part of leaflet
        this.$refs.mymap.mapObject.invalidateSize();
      }, 100);
    }
  }
}

Now everything should be fine:

map should not spill outside the modal

map should be visible (duh)

map squares should be downloaded when within map body

Here's my full code, it contains some stuff specific to my app but overall it contains all of the code snippets above.


问:
How to get successive random subsamples?
I'm aiming to randomly take a sample of items from a list and then take a sample from that new list until only one item is left in the list.

Code:

```<code>from random import sample

exampleList = ["Gary","Kerry","Larry","Bob","Frank","Joshua"]

def reduce(List):
    newList = sample(List, random.randint(1, len(List)))
    return newList

reduce(reduce(reduce(reduce(exampleList)))) #<-- I want to avoid doing this#
</code>```

答:
You can use a for loop:

```<code>from random import sample, seed

seed(0)  # set the seed

chosen = [exampleList[:]]  # start with a copy of the original list

for n in range(len(exampleList)-1, 0, -1):
    chosen.append(sample(chosen[-1], n))  # successively append samples
print(chosen)
#[['Gary', 'Kerry', 'Larry', 'Bob', 'Frank', 'Joshua'],
# ['Bob', 'Joshua', 'Gary', 'Kerry', 'Larry'],
# ['Kerry', 'Gary', 'Joshua', 'Larry'],
# ['Gary', 'Joshua', 'Kerry'],
# ['Joshua', 'Gary'],
# ['Joshua']]
</code>```

You initialize the output list to contain a copy of the original list. Then loop over values of n from len(exampleList) - 1 through 1 and take a sample of that size from the last element of the output list.

Body:
I'm aiming to randomly take a sample of items from a list and then take a sample from that new list until only one item is left in the list.

Code:

from random import sample

exampleList = ["Gary","Kerry","Larry","Bob","Frank","Joshua"]

def reduce(List):
    newList = sample(List, random.randint(1, len(List)))
    return newList

reduce(reduce(reduce(reduce(exampleList)))) #<-- I want to avoid doing this#

Body:
You can use a for loop:

from random import sample, seed

seed(0)  # set the seed

chosen = [exampleList[:]]  # start with a copy of the original list

for n in range(len(exampleList)-1, 0, -1):
    chosen.append(sample(chosen[-1], n))  # successively append samples
print(chosen)
#[['Gary', 'Kerry', 'Larry', 'Bob', 'Frank', 'Joshua'],
# ['Bob', 'Joshua', 'Gary', 'Kerry', 'Larry'],
# ['Kerry', 'Gary', 'Joshua', 'Larry'],
# ['Gary', 'Joshua', 'Kerry'],
# ['Joshua', 'Gary'],
# ['Joshua']]

You initialize the output list to contain a copy of the original list. Then loop over values of n from len(exampleList) - 1 through 1 and take a sample of that size from the last element of the output list.


问:
ffmpeg rotate and resize
I'm trying to resize a movie and to rotate it counter-clockwise using ffmpeg.
I can achieve one or the other ok individually

ffmpeg -i MVI_8189.MOV -vf "transpose=2" -ss 00:00:12 -t 00:00:05 rotate.MOV

OR

ffmpeg -i MVI_8189.MOV -s 720x406 -ss 00:00:12 -t 00:00:05 resize.MOV

but if I try to do both, either-

ffmpeg -i MVI_8189.MOV -s 720x406 -ss 00:00:12 -t 00:00:05 resize.MOV

ffmpeg -i resize.MOV -vf "transpose=2" toutp.MOV

OR

ffmpeg -i MVI_8189.MOV -vf "transpose=2" -ss 00:00:12 -t 00:00:05 rotate.MOV

ffmpeg -i rotate.MOV -s 406x720  toutp.MOV

the final movie does not play, only audio, no video; neither previewing in Finder, nor in Quicktime. More seriously once I have attempted to play it, I can't then play any other movie whatsoever (only audio) - quicktime won't quit, constantly need to force-quit it. The only way to then restore seems to be reboot OS-X

This though does work -

ffmpeg -i MVI_8189.MOV -vf "transpose=2" -ss 00:00:12 -t 00:00:05 rotate.MOV

ffmpeg -i rotate.MOV -s 720x406 toutp.MOV

but doesn't do what I want - it stretches the movie in the wrong direction

Any ideas?

ffmpeg version 1.0.git Copyright (c) 2000-2012 the FFmpeg developers
built on Dec 24 2012 18:43:25 with llvm-gcc 4.2.1 (LLVM build 2336.1.00)

MAC OSX 10.7.5

==========
output from

```<code>ffmpeg -i MVI_8189.MOV -vf "transpose=2" -ss 00:00:12 -t 00:00:05 rotate.MOV
ffmpeg -i rotate.MOV -s 406x720  toutp.MOV

ffmpeg version 1.0.git Copyright (c) 2000-2012 the FFmpeg developers
  built on Dec 24 2012 18:43:25 with llvm-gcc 4.2.1 (LLVM build 2336.1.00)
  configuration: --prefix=/usr/local --enable-shared --disable-mmx --enable-libmp3lame --enable-gpl --enable-zlib --enable-libvorbis --enable-libfaac --enable-nonfree --enable-libx264 --enable-pthreads
  libavutil      52. 12.100 / 52. 12.100
  libavcodec     54. 81.100 / 54. 81.100
  libavformat    54. 49.102 / 54. 49.102
  libavdevice    54.  3.102 / 54.  3.102
  libavfilter     3. 29.101 /  3. 29.101
  libswscale      2.  1.103 /  2.  1.103
  libswresample   0. 17.102 /  0. 17.102
  libpostproc    52.  2.100 / 52.  2.100
Guessed Channel Layout for  Input Stream #0.1 : stereo
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'MVI_8189.MOV':
  Metadata:
    major_brand     : qt
    minor_version   : 537331968
    compatible_brands: qt  CAEP
    creation_time   : 2014-08-17 23:13:43
  Duration: 00:01:32.40, start: 0.000000, bitrate: 44677 kb/s
    Stream #0:0(eng): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuvj420p, 1920x1080, 43132 kb/s, 25 fps, 25 tbr, 25k tbn, 50k tbc
    Metadata:
      creation_time   : 2014-08-17 23:13:43
    Stream #0:1(eng): Audio: pcm_s16le (sowt / 0x74776F73), 48000 Hz, stereo, s16, 1536 kb/s
    Metadata:
      creation_time   : 2014-08-17 23:13:43
[libx264 @ 0x7fc67c043600] using cpu capabilities: MMX2 SSE2Fast SSSE3 FastShuffle SSE4.2 AVX
[libx264 @ 0x7fc67c043600] profile High, level 4.0
[libx264 @ 0x7fc67c043600] 264 - core 128 - H.264/MPEG-4 AVC codec - Copyleft 2003-2012 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, mov, to 'rotate.MOV':
  Metadata:
    major_brand     : qt
    minor_version   : 537331968
    compatible_brands: qt  CAEP
    encoder         : Lavf54.49.102
    Stream #0:0(eng): Video: h264 (avc1 / 0x31637661), yuvj420p, 1080x1920, q=-1--1, 12800 tbn, 25 tbc
    Metadata:
      creation_time   : 2014-08-17 23:13:43
    Stream #0:1(eng): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, s16, 128 kb/s
    Metadata:
      creation_time   : 2014-08-17 23:13:43
Stream mapping:
  Stream #0:0 -> #0:0 (h264 -> libx264)
  Stream #0:1 -> #0:1 (pcm_s16le -> libfaac)
Press [q] to stop, [?] for help
frame=  125 fps=5.7 q=-2.0 Lsize=    6394kB time=00:00:05.00 bitrate=10470.5kbits/s    /s
video:6322kB audio:67kB subtitle:0 global headers:0kB muxing overhead 0.079207%
[libx264 @ 0x7fc67c043600] frame I:1     Avg QP:25.87  size:113032
[libx264 @ 0x7fc67c043600] frame P:65    Avg QP:25.78  size: 64251
[libx264 @ 0x7fc67c043600] frame B:59    Avg QP:26.73  size: 37017
[libx264 @ 0x7fc67c043600] consecutive B-frames:  5.6% 94.4%  0.0%  0.0%
[libx264 @ 0x7fc67c043600] mb I  I16..4: 10.7% 79.9%  9.3%
[libx264 @ 0x7fc67c043600] mb P  I16..4:  3.6% 12.0%  0.3%  P16..4: 52.0% 19.1% 11.3%  0.0%  0.0%    skip: 1.7%
[libx264 @ 0x7fc67c043600] mb B  I16..4:  0.9%  1.7%  0.0%  B16..8: 45.4%  5.1%  0.8%  direct:24.2%  skip:21.9%  L0:50.1% L1:44.5% BI: 5.3%
[libx264 @ 0x7fc67c043600] 8x8 transform intra:74.5% inter:79.5%
[libx264 @ 0x7fc67c043600] coded y,uvDC,uvAC intra: 59.4% 94.3% 79.5% inter: 38.2% 80.5% 30.1%
[libx264 @ 0x7fc67c043600] i16 v,h,dc,p: 30% 21% 22% 28%
[libx264 @ 0x7fc67c043600] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 18% 14% 24%  6%  8%  9%  7%  8%  7%
[libx264 @ 0x7fc67c043600] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 28% 18% 17%  6%  7%  8%  6%  6%  4%
[libx264 @ 0x7fc67c043600] i8c dc,h,v,p: 60% 14% 18%  8%
[libx264 @ 0x7fc67c043600] Weighted P-Frames: Y:0.0% UV:0.0%
[libx264 @ 0x7fc67c043600] ref P L0: 43.9% 12.6% 26.8% 16.7%
[libx264 @ 0x7fc67c043600] ref B L0: 68.6% 31.4%
[libx264 @ 0x7fc67c043600] kb/s:10357.28
ffmpeg version 1.0.git Copyright (c) 2000-2012 the FFmpeg developers
  built on Dec 24 2012 18:43:25 with llvm-gcc 4.2.1 (LLVM build 2336.1.00)
  configuration: --prefix=/usr/local --enable-shared --disable-mmx --enable-libmp3lame --enable-gpl --enable-zlib --enable-libvorbis --enable-libfaac --enable-nonfree --enable-libx264 --enable-pthreads
  libavutil      52. 12.100 / 52. 12.100
  libavcodec     54. 81.100 / 54. 81.100
  libavformat    54. 49.102 / 54. 49.102
  libavdevice    54.  3.102 / 54.  3.102
  libavfilter     3. 29.101 /  3. 29.101
  libswscale      2.  1.103 /  2.  1.103
  libswresample   0. 17.102 /  0. 17.102
  libpostproc    52.  2.100 / 52.  2.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'rotate.MOV':
  Metadata:
    major_brand     : qt
    minor_version   : 512
    compatible_brands: qt
    encoder         : Lavf54.49.102
  Duration: 00:00:05.01, start: 0.010667, bitrate: 10446 kb/s
    Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuvj420p, 1080x1920, 10358 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc
    Metadata:
      handler_name    : DataHandler
    Stream #0:1(eng): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 109 kb/s
    Metadata:
      handler_name    : DataHandler
[libx264 @ 0x7fcf1c05ba00] using cpu capabilities: MMX2 SSE2Fast SSSE3 FastShuffle SSE4.2 AVX
[libx264 @ 0x7fcf1c05ba00] profile High, level 3.0
[libx264 @ 0x7fcf1c05ba00] 264 - core 128 - H.264/MPEG-4 AVC codec - Copyleft 2003-2012 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, mov, to 'toutp.MOV':
  Metadata:
    major_brand     : qt
    minor_version   : 512
    compatible_brands: qt
    encoder         : Lavf54.49.102
    Stream #0:0(eng): Video: h264 (avc1 / 0x31637661), yuvj420p, 406x720, q=-1--1, 12800 tbn, 25 tbc
    Metadata:
      handler_name    : DataHandler
    Stream #0:1(eng): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, s16, 128 kb/s
    Metadata:
      handler_name    : DataHandler
Stream mapping:
  Stream #0:0 -> #0:0 (h264 -> libx264)
  Stream #0:1 -> #0:1 (aac -> libfaac)
Press [q] to stop, [?] for help
frame=  125 fps= 32 q=-2.0 Lsize=     469kB time=00:00:05.01 bitrate= 766.2kbits/s
video:396kB audio:68kB subtitle:0 global headers:0kB muxing overhead 1.088481%
[libx264 @ 0x7fcf1c05ba00] frame I:1     Avg QP:24.20  size: 31395
[libx264 @ 0x7fcf1c05ba00] frame P:42    Avg QP:24.51  size:  7137
[libx264 @ 0x7fcf1c05ba00] frame B:82    Avg QP:27.71  size:   893
[libx264 @ 0x7fcf1c05ba00] consecutive B-frames:  0.8% 16.0% 57.6% 25.6%
[libx264 @ 0x7fcf1c05ba00] mb I  I16..4:  7.0% 62.2% 30.8%
[libx264 @ 0x7fcf1c05ba00] mb P  I16..4:  0.2%  0.8%  0.1%  P16..4: 52.8% 18.7% 12.5%  0.0%  0.0%    skip:14.9%
[libx264 @ 0x7fcf1c05ba00] mb B  I16..4:  0.0%  0.0%  0.0%  B16..8: 30.0%  0.8%  0.1%  direct: 0.9%  skip:68.2%  L0:36.0% L1:62.1% BI: 2.0%
[libx264 @ 0x7fcf1c05ba00] 8x8 transform intra:66.4% inter:78.3%
[libx264 @ 0x7fcf1c05ba00] coded y,uvDC,uvAC intra: 79.3% 93.6% 84.9% inter: 13.6% 32.2% 10.4%
[libx264 @ 0x7fcf1c05ba00] i16 v,h,dc,p: 50% 19%  7% 24%
[libx264 @ 0x7fcf1c05ba00] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 20% 20% 11%  5%  8% 10%  9%  7%  8%
[libx264 @ 0x7fcf1c05ba00] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 27% 22%  8%  5%  8%  8% 10%  5%  5%
[libx264 @ 0x7fcf1c05ba00] i8c dc,h,v,p: 42% 22% 24% 13%
[libx264 @ 0x7fcf1c05ba00] Weighted P-Frames: Y:0.0% UV:0.0%
[libx264 @ 0x7fcf1c05ba00] ref P L0: 48.7% 16.3% 25.6%  9.4%
[libx264 @ 0x7fcf1c05ba00] ref B L0: 73.7% 21.3%  5.0%
[libx264 @ 0x7fcf1c05ba00] ref B L1: 90.7%  9.3%
[libx264 @ 0x7fcf1c05ba00] kb/s:647.04
</code>```

答:
Simpler version:

ffmpeg -i input.mp4 -vf "transpose=2,scale=720:-2" output.mp4

The above command will:

Rotate the video 90 degrees counterclockwise

Scale so the (new) horizontal resolution is 720

Scale so the new vertical resolution is whatever it needs to be to maintain the aspect ratio of the original file

The new vertical will be divisible by 2, which is required by some compression codecs, e.g h265

Title: ffmpeg rotate and resize

Body:
I'm trying to resize a movie and to rotate it counter-clockwise using ffmpeg.
I can achieve one or the other ok individually

ffmpeg -i MVI_8189.MOV -vf "transpose=2" -ss 00:00:12 -t 00:00:05 rotate.MOV

OR

ffmpeg -i MVI_8189.MOV -s 720x406 -ss 00:00:12 -t 00:00:05 resize.MOV

but if I try to do both, either-

ffmpeg -i MVI_8189.MOV -s 720x406 -ss 00:00:12 -t 00:00:05 resize.MOV

ffmpeg -i resize.MOV -vf "transpose=2" toutp.MOV

OR

ffmpeg -i MVI_8189.MOV -vf "transpose=2" -ss 00:00:12 -t 00:00:05 rotate.MOV

ffmpeg -i rotate.MOV -s 406x720  toutp.MOV

the final movie does not play, only audio, no video; neither previewing in Finder, nor in Quicktime. More seriously once I have attempted to play it, I can't then play any other movie whatsoever (only audio) - quicktime won't quit, constantly need to force-quit it. The only way to then restore seems to be reboot OS-X

This though does work -

ffmpeg -i MVI_8189.MOV -vf "transpose=2" -ss 00:00:12 -t 00:00:05 rotate.MOV

ffmpeg -i rotate.MOV -s 720x406 toutp.MOV

but doesn't do what I want - it stretches the movie in the wrong direction

Any ideas?

ffmpeg version 1.0.git Copyright (c) 2000-2012 the FFmpeg developers
built on Dec 24 2012 18:43:25 with llvm-gcc 4.2.1 (LLVM build 2336.1.00)

MAC OSX 10.7.5

==========
output from

ffmpeg -i MVI_8189.MOV -vf "transpose=2" -ss 00:00:12 -t 00:00:05 rotate.MOV
ffmpeg -i rotate.MOV -s 406x720  toutp.MOV

ffmpeg version 1.0.git Copyright (c) 2000-2012 the FFmpeg developers
  built on Dec 24 2012 18:43:25 with llvm-gcc 4.2.1 (LLVM build 2336.1.00)
  configuration: --prefix=/usr/local --enable-shared --disable-mmx --enable-libmp3lame --enable-gpl --enable-zlib --enable-libvorbis --enable-libfaac --enable-nonfree --enable-libx264 --enable-pthreads
  libavutil      52. 12.100 / 52. 12.100
  libavcodec     54. 81.100 / 54. 81.100
  libavformat    54. 49.102 / 54. 49.102
  libavdevice    54.  3.102 / 54.  3.102
  libavfilter     3. 29.101 /  3. 29.101
  libswscale      2.  1.103 /  2.  1.103
  libswresample   0. 17.102 /  0. 17.102
  libpostproc    52.  2.100 / 52.  2.100
Guessed Channel Layout for  Input Stream #0.1 : stereo
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'MVI_8189.MOV':
  Metadata:
    major_brand     : qt
    minor_version   : 537331968
    compatible_brands: qt  CAEP
    creation_time   : 2014-08-17 23:13:43
  Duration: 00:01:32.40, start: 0.000000, bitrate: 44677 kb/s
    Stream #0:0(eng): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuvj420p, 1920x1080, 43132 kb/s, 25 fps, 25 tbr, 25k tbn, 50k tbc
    Metadata:
      creation_time   : 2014-08-17 23:13:43
    Stream #0:1(eng): Audio: pcm_s16le (sowt / 0x74776F73), 48000 Hz, stereo, s16, 1536 kb/s
    Metadata:
      creation_time   : 2014-08-17 23:13:43
[libx264 @ 0x7fc67c043600] using cpu capabilities: MMX2 SSE2Fast SSSE3 FastShuffle SSE4.2 AVX
[libx264 @ 0x7fc67c043600] profile High, level 4.0
[libx264 @ 0x7fc67c043600] 264 - core 128 - H.264/MPEG-4 AVC codec - Copyleft 2003-2012 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, mov, to 'rotate.MOV':
  Metadata:
    major_brand     : qt
    minor_version   : 537331968
    compatible_brands: qt  CAEP
    encoder         : Lavf54.49.102
    Stream #0:0(eng): Video: h264 (avc1 / 0x31637661), yuvj420p, 1080x1920, q=-1--1, 12800 tbn, 25 tbc
    Metadata:
      creation_time   : 2014-08-17 23:13:43
    Stream #0:1(eng): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, s16, 128 kb/s
    Metadata:
      creation_time   : 2014-08-17 23:13:43
Stream mapping:
  Stream #0:0 -> #0:0 (h264 -> libx264)
  Stream #0:1 -> #0:1 (pcm_s16le -> libfaac)
Press [q] to stop, [?] for help
frame=  125 fps=5.7 q=-2.0 Lsize=    6394kB time=00:00:05.00 bitrate=10470.5kbits/s    /s
video:6322kB audio:67kB subtitle:0 global headers:0kB muxing overhead 0.079207%
[libx264 @ 0x7fc67c043600] frame I:1     Avg QP:25.87  size:113032
[libx264 @ 0x7fc67c043600] frame P:65    Avg QP:25.78  size: 64251
[libx264 @ 0x7fc67c043600] frame B:59    Avg QP:26.73  size: 37017
[libx264 @ 0x7fc67c043600] consecutive B-frames:  5.6% 94.4%  0.0%  0.0%
[libx264 @ 0x7fc67c043600] mb I  I16..4: 10.7% 79.9%  9.3%
[libx264 @ 0x7fc67c043600] mb P  I16..4:  3.6% 12.0%  0.3%  P16..4: 52.0% 19.1% 11.3%  0.0%  0.0%    skip: 1.7%
[libx264 @ 0x7fc67c043600] mb B  I16..4:  0.9%  1.7%  0.0%  B16..8: 45.4%  5.1%  0.8%  direct:24.2%  skip:21.9%  L0:50.1% L1:44.5% BI: 5.3%
[libx264 @ 0x7fc67c043600] 8x8 transform intra:74.5% inter:79.5%
[libx264 @ 0x7fc67c043600] coded y,uvDC,uvAC intra: 59.4% 94.3% 79.5% inter: 38.2% 80.5% 30.1%
[libx264 @ 0x7fc67c043600] i16 v,h,dc,p: 30% 21% 22% 28%
[libx264 @ 0x7fc67c043600] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 18% 14% 24%  6%  8%  9%  7%  8%  7%
[libx264 @ 0x7fc67c043600] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 28% 18% 17%  6%  7%  8%  6%  6%  4%
[libx264 @ 0x7fc67c043600] i8c dc,h,v,p: 60% 14% 18%  8%
[libx264 @ 0x7fc67c043600] Weighted P-Frames: Y:0.0% UV:0.0%
[libx264 @ 0x7fc67c043600] ref P L0: 43.9% 12.6% 26.8% 16.7%
[libx264 @ 0x7fc67c043600] ref B L0: 68.6% 31.4%
[libx264 @ 0x7fc67c043600] kb/s:10357.28
ffmpeg version 1.0.git Copyright (c) 2000-2012 the FFmpeg developers
  built on Dec 24 2012 18:43:25 with llvm-gcc 4.2.1 (LLVM build 2336.1.00)
  configuration: --prefix=/usr/local --enable-shared --disable-mmx --enable-libmp3lame --enable-gpl --enable-zlib --enable-libvorbis --enable-libfaac --enable-nonfree --enable-libx264 --enable-pthreads
  libavutil      52. 12.100 / 52. 12.100
  libavcodec     54. 81.100 / 54. 81.100
  libavformat    54. 49.102 / 54. 49.102
  libavdevice    54.  3.102 / 54.  3.102
  libavfilter     3. 29.101 /  3. 29.101
  libswscale      2.  1.103 /  2.  1.103
  libswresample   0. 17.102 /  0. 17.102
  libpostproc    52.  2.100 / 52.  2.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'rotate.MOV':
  Metadata:
    major_brand     : qt
    minor_version   : 512
    compatible_brands: qt
    encoder         : Lavf54.49.102
  Duration: 00:00:05.01, start: 0.010667, bitrate: 10446 kb/s
    Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuvj420p, 1080x1920, 10358 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc
    Metadata:
      handler_name    : DataHandler
    Stream #0:1(eng): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 109 kb/s
    Metadata:
      handler_name    : DataHandler
[libx264 @ 0x7fcf1c05ba00] using cpu capabilities: MMX2 SSE2Fast SSSE3 FastShuffle SSE4.2 AVX
[libx264 @ 0x7fcf1c05ba00] profile High, level 3.0
[libx264 @ 0x7fcf1c05ba00] 264 - core 128 - H.264/MPEG-4 AVC codec - Copyleft 2003-2012 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, mov, to 'toutp.MOV':
  Metadata:
    major_brand     : qt
    minor_version   : 512
    compatible_brands: qt
    encoder         : Lavf54.49.102
    Stream #0:0(eng): Video: h264 (avc1 / 0x31637661), yuvj420p, 406x720, q=-1--1, 12800 tbn, 25 tbc
    Metadata:
      handler_name    : DataHandler
    Stream #0:1(eng): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, s16, 128 kb/s
    Metadata:
      handler_name    : DataHandler
Stream mapping:
  Stream #0:0 -> #0:0 (h264 -> libx264)
  Stream #0:1 -> #0:1 (aac -> libfaac)
Press [q] to stop, [?] for help
frame=  125 fps= 32 q=-2.0 Lsize=     469kB time=00:00:05.01 bitrate= 766.2kbits/s
video:396kB audio:68kB subtitle:0 global headers:0kB muxing overhead 1.088481%
[libx264 @ 0x7fcf1c05ba00] frame I:1     Avg QP:24.20  size: 31395
[libx264 @ 0x7fcf1c05ba00] frame P:42    Avg QP:24.51  size:  7137
[libx264 @ 0x7fcf1c05ba00] frame B:82    Avg QP:27.71  size:   893
[libx264 @ 0x7fcf1c05ba00] consecutive B-frames:  0.8% 16.0% 57.6% 25.6%
[libx264 @ 0x7fcf1c05ba00] mb I  I16..4:  7.0% 62.2% 30.8%
[libx264 @ 0x7fcf1c05ba00] mb P  I16..4:  0.2%  0.8%  0.1%  P16..4: 52.8% 18.7% 12.5%  0.0%  0.0%    skip:14.9%
[libx264 @ 0x7fcf1c05ba00] mb B  I16..4:  0.0%  0.0%  0.0%  B16..8: 30.0%  0.8%  0.1%  direct: 0.9%  skip:68.2%  L0:36.0% L1:62.1% BI: 2.0%
[libx264 @ 0x7fcf1c05ba00] 8x8 transform intra:66.4% inter:78.3%
[libx264 @ 0x7fcf1c05ba00] coded y,uvDC,uvAC intra: 79.3% 93.6% 84.9% inter: 13.6% 32.2% 10.4%
[libx264 @ 0x7fcf1c05ba00] i16 v,h,dc,p: 50% 19%  7% 24%
[libx264 @ 0x7fcf1c05ba00] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 20% 20% 11%  5%  8% 10%  9%  7%  8%
[libx264 @ 0x7fcf1c05ba00] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 27% 22%  8%  5%  8%  8% 10%  5%  5%
[libx264 @ 0x7fcf1c05ba00] i8c dc,h,v,p: 42% 22% 24% 13%
[libx264 @ 0x7fcf1c05ba00] Weighted P-Frames: Y:0.0% UV:0.0%
[libx264 @ 0x7fcf1c05ba00] ref P L0: 48.7% 16.3% 25.6%  9.4%
[libx264 @ 0x7fcf1c05ba00] ref B L0: 73.7% 21.3%  5.0%
[libx264 @ 0x7fcf1c05ba00] ref B L1: 90.7%  9.3%
[libx264 @ 0x7fcf1c05ba00] kb/s:647.04


问:
EFS mounting in another AWS account?
I have an odd request from management (is there any other kind?) and was hoping to get some info here.

Is there a way to mount an EFS volume from AWS account A to a windows EC2 instance in AWS account B?

答: This is now supported in AWS EFS - https://aws.amazon.com/about-aws/whats-new/2018/11/amazon-efs-now-supports-access-across-accounts-and-vpcs/</p>

Title: EFS mounting in another AWS account?


问:
What does "The constructor ... is ambiguous" mean?
I would like to know what the error message in Eclipse means:

The constructor Case(Problem, Solution, double, CaseSource) is ambiguous

答:
This means that you have two constructors with the same signature, or that you're trying to create a new instance of Case with parameters that could match more than one constructor.

In your case :

```<code>Case(Problem, Solution, double, CaseSource)
</code>```

Java create methods (constructors) signatures with the parameter types. You can have two methods with the same similar parameter types, and therefore it may be possible to generate ambiguous calls by providing ambiguous arguments that could match multiple method (constructor) signatures.

You may reproduce this error (which is not eclipse's fault) with this code :

```<code>class A {
    public A(String a) { }
    public A(Integer a) { }

    static public void main(String...args) {
        new A(null);    // <== constructor is ambiguous
    }
}
</code>```

Body:
This means that you have two constructors with the same signature, or that you're trying to create a new instance of Case with parameters that could match more than one constructor.

In your case :

Case(Problem, Solution, double, CaseSource)

Java create methods (constructors) signatures with the parameter types. You can have two methods with the same similar parameter types, and therefore it may be possible to generate ambiguous calls by providing ambiguous arguments that could match multiple method (constructor) signatures.

You may reproduce this error (which is not eclipse's fault) with this code :

class A {
    public A(String a) { }
    public A(Integer a) { }

    static public void main(String...args) {
        new A(null);    // <== constructor is ambiguous
    }
}


问:
Troubles installing MySQL 8.0 on Ubuntu 18.04
I have a freshly installed Ubuntu 18.04 server. I want to install MySQL 8.0 on it so I issued the following commands that I found on the web

```<code> wget -c https://dev.mysql.com/get/mysql-apt-config_0.8.10-1_all.deb
 dpkg -i mysql-apt-config_0.8.10-1_all.deb
</code>```

After executing the dpkg command, I get a screen to choose the configuration that I want. Of course I choose MySQL 8.0. I expected to see something like this:

```<code>Selecting previously unselected package mysql-apt-config.
(Reading database ... 51260 files and directories currently installed.)
Preparing to unpack mysql-apt-config_0.8.10-1_all.deb ...
Unpacking mysql-apt-config (0.8.10-1) ...
Setting up mysql-apt-config (0.8.10-1) ...
</code>```

but, I only saw this warning:

```<code>Warning: apt-key should not be used in scripts (called from postinst maintainerscript of the package mysql-apt-config)
</code>```

After that, I can only install MySQL 5.7 and not 8.0.

答:
Removing, purging and reinstalling the mysql-apt-config package fixed this for me:

```<code>dpkg --remove mysql-apt-config
dpkg --purge mysql-apt-config
dpkg -i mysql-apt-config_0.8.13-1_all.deb
</code>```

Body:
I have a freshly installed Ubuntu 18.04 server. I want to install MySQL 8.0 on it so I issued the following commands that I found on the web

 wget -c https://dev.mysql.com/get/mysql-apt-config_0.8.10-1_all.deb
 dpkg -i mysql-apt-config_0.8.10-1_all.deb

After executing the dpkg command, I get a screen to choose the configuration that I want. Of course I choose MySQL 8.0. I expected to see something like this:

Selecting previously unselected package mysql-apt-config.
(Reading database ... 51260 files and directories currently installed.)
Preparing to unpack mysql-apt-config_0.8.10-1_all.deb ...
Unpacking mysql-apt-config (0.8.10-1) ...
Setting up mysql-apt-config (0.8.10-1) ...

but, I only saw this warning:

Warning: apt-key should not be used in scripts (called from postinst maintainerscript of the package mysql-apt-config)

After that, I can only install MySQL 5.7 and not 8.0.

Body:
Removing, purging and reinstalling the mysql-apt-config package fixed this for me:

dpkg --remove mysql-apt-config
dpkg --purge mysql-apt-config
dpkg -i mysql-apt-config_0.8.13-1_all.deb


问:
Ruby two strings in an IF condition
In my rails project I've if statement with string conditions which doesn't work.

```<code>  if shop.details['company_role'] == 'CEO' || 'founder'
        'Other'
      else
        shop.details['customer_kind']
      end
  end
</code>```

When I've case with company_role = founder it didn't return me 'Other' but customer_kind

答:
The premise is a little off.  The if statement works, but it's not producing the results that you expect.  It's basically doing the equivalent of this:

shop.details['company_role'] == 'CEO' # is this true? then stop
  | "founder"                           # is this true?  yes, it's always truthy

The solutions provided will all work.  Your choice mostly depends on your code style.  I'd go with the second option because I personally like the test with an emphasis on the tested data.

Two further suggestions.  First, the test itself could be extracted to a method.  This would improve readability of your code.

```<code>def shop_type
  if executive?
    'Other'
  else
    shop.details['customer_kind']
  end
  # alternate: executive? ? 'Other' : shop.details['customer_kind']
end

def executive?
  shop.details['company_role'].in?('CEO','founder')
end
</code>```

Lastly, it strikes me that the decision about whether or not a Shop includes an "executive?" seems to be useful information in a number of contexts.  As such, it looks like the executive? method would be better placed inside the Shop model so that knowledge of the internal organization of the Shop does not leak all over your system.

```<code>shop.executive? ? 'Other' : shop.details['customer_kind']

class Shop
  ...
  def executive?
    shop.details['company_role'].in?('CEO','founder')
  end
end
</code>```

Title: Ruby two strings in an IF condition

Body:
In my rails project I've if statement with string conditions which doesn't work.

  if shop.details['company_role'] == 'CEO' || 'founder'
        'Other'
      else
        shop.details['customer_kind']
      end
  end

When I've case with company_role = founder it didn't return me 'Other' but customer_kind

Body:
The premise is a little off.  The if statement works, but it's not producing the results that you expect.  It's basically doing the equivalent of this:

shop.details['company_role'] == 'CEO' # is this true? then stop
  | "founder"                           # is this true?  yes, it's always truthy

The solutions provided will all work.  Your choice mostly depends on your code style.  I'd go with the second option because I personally like the test with an emphasis on the tested data.

Two further suggestions.  First, the test itself could be extracted to a method.  This would improve readability of your code.

def shop_type
  if executive?
    'Other'
  else
    shop.details['customer_kind']
  end
  # alternate: executive? ? 'Other' : shop.details['customer_kind']
end

def executive?
  shop.details['company_role'].in?('CEO','founder')
end

Lastly, it strikes me that the decision about whether or not a Shop includes an "executive?" seems to be useful information in a number of contexts.  As such, it looks like the executive? method would be better placed inside the Shop model so that knowledge of the internal organization of the Shop does not leak all over your system.

shop.executive? ? 'Other' : shop.details['customer_kind']

class Shop
  ...
  def executive?
    shop.details['company_role'].in?('CEO','founder')
  end
end


问:
Can a proprietary data store be proxied in Nexus
In our company we have a data store that holds a wide variety of objects. This data store could be seen as a remote repository with a proprietary format. We would to make those objects available in a Nexus Repository Manager in a similar fashion as a remote Maven repository.

I wonder, would it be possible to create a proxy to this non-standard proprietary repository? Our proprietary data store has some version information, that we could map to a standard repository format.

Any help like an example or pointing me to documentation or existing plugins would be greatly appreciated.

答:
You can proxy almost anything available via http(s) using a raw format proxy in nexus. Now if you want to proxy something that is not maven to a maven format, it's not possible.

If you have some version info you can use, I imagine you can create a script that would get a set of artifacts from your company repo and register them correctly using the nexus API in a maven hosted repo. That would not be a proxy but a partial async mirror.


问:
My search function doesnt work if we search again because the original array gets changed
```<code><input type="text" [(ngModel)]="searchTerm" (input)="search()">
</code>```

We type something to search the first time it gets searched but again if we search then no records are found because the original array records is changed it would only consist of the records which are searched and not all the records how to deal with this problem.

I could create a second array to keep a copy of all the records and assign it to the original array in the else if condition but that would only work if we empty the search box and not if we search and type again without emptying the search box to the last character.

The records are shown in the table with ngfor. The search function is for that table

```<code> searchTerm : any;
    records: any;  //array of objects

    search(){
 if(this.searchTerm !== ""){
     this.records = this.records.filter((res: any)=>{
            return (res.name && res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase()));
          });
} else if(this.searchTerm === "") {

}
    }
</code>```

答:
Angular pipes are best solution for this scenario. Create a pipe for search it will filter and render filtered array in DOM but will not update your original array

Angular Pipe

Similar Question

Body:
<input type="text" [(ngModel)]="searchTerm" (input)="search()">

We type something to search the first time it gets searched but again if we search then no records are found because the original array records is changed it would only consist of the records which are searched and not all the records how to deal with this problem.

I could create a second array to keep a copy of all the records and assign it to the original array in the else if condition but that would only work if we empty the search box and not if we search and type again without emptying the search box to the last character.

The records are shown in the table with ngfor. The search function is for that table

 searchTerm : any;
    records: any;  //array of objects

    search(){
 if(this.searchTerm !== ""){
     this.records = this.records.filter((res: any)=>{
            return (res.name && res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase()));
          });
} else if(this.searchTerm === "") {

}
    }


问:
Java Extract a String from a String
I am parsing a csv file with Apache Commons CSVRecord and CSVFormat in Java
I got the following record in String format
Records :  CSVRecord [comment=null, mapping={Id=0, FirstName=1, LastName=2},
recordNumber=1, values=[1, John, Wayne]]

I need to extract the values only For ex: 1, John, Wayne

Used the following options to get the result.

```<code>String[] split = record.split("values=\\[");
String result = split[1].substring(0, split[1].length() - 2);
</code>```

My Question is: Is there a better option(Faster) than this in Java?

答:
Try this:</p>

```<code>String txt = "CSVRecord [comment=null, mapping={Id=0, FirstName=1, LastName=2}, recordNumber=1, values=[1, John, Wayne]]";

String[] sub = txt.substring(txt.indexOf("values=[")).split("[\\[\\]]");

System.out.println(sub[1]);
</code>```

Title: Java Extract a String from a String

Body:
I am parsing a csv file with Apache Commons CSVRecord and CSVFormat in Java
I got the following record in String format
Records :  CSVRecord [comment=null, mapping={Id=0, FirstName=1, LastName=2},
recordNumber=1, values=[1, John, Wayne]]

I need to extract the values only For ex: 1, John, Wayne

Used the following options to get the result.

String[] split = record.split("values=\\[");
String result = split[1].substring(0, split[1].length() - 2);

My Question is: Is there a better option(Faster) than this in Java?

Body:
Try this:

String txt = "CSVRecord [comment=null, mapping={Id=0, FirstName=1, LastName=2}, recordNumber=1, values=[1, John, Wayne]]";

String[] sub = txt.substring(txt.indexOf("values=[")).split("[\\[\\]]");

System.out.println(sub[1]);


问:
How to get current window pageYOffset in styled component?
Im struggling with translate animation which depends on scrollYOffset of a window.

I've got something like this :

```<code>const StyledHeading = styled.h1`
  font-size: ${({ theme }) => theme.fontSize.l};
  letter-spacing: 1px;
  font-family: ${({ theme }) => theme.font.firaSans};
  margin: 0;
  transition: 0.25s ease-in-out;
  transform: translateX(${({ offset }) => (offset > 100 ? '-50px' : '0px')});
`;

export default function Navbar() {
  const [offset, setOffset] = useState(window.pageYOffset);

  useEffect(() => {
    window.addEventListener('scroll', () => {
      setOffset(window.pageYOffset);
    });
  });

  return (
    <StyledHeader >
      <StyledWrapper>
        <StyledHeading offset={offset}>
          Bookphiles <i className="fas fa-book-open" />
        </StyledHeading>
        <nav>
          <NavLinks  />
        </nav>
      </StyledWrapper>
    </StyledHeader>
  );
}
</code>```

But its seems to be done in very inefficient way, because every scroll causes DOM rerender. Can this be done in some better way?

答:
Try using a throttle or debounce function from lodash to limit the number of times your event handler function is executed. This way the event handler will only be executed at most every 200 milliseconds:

```<code>window.addEventListener('scroll', _.throttle(() => {
  setOffset(window.pageYOffset);
}, 200));
</code>```

This is a good article that explains this idea in more detail and provides more examples: https://css-tricks.com/debouncing-throttling-explained-examples/

Body:
Im struggling with translate animation which depends on scrollYOffset of a window.

I've got something like this :

const StyledHeading = styled.h1`
  font-size: ${({ theme }) => theme.fontSize.l};
  letter-spacing: 1px;
  font-family: ${({ theme }) => theme.font.firaSans};
  margin: 0;
  transition: 0.25s ease-in-out;
  transform: translateX(${({ offset }) => (offset > 100 ? '-50px' : '0px')});
`;

export default function Navbar() {
  const [offset, setOffset] = useState(window.pageYOffset);

  useEffect(() => {
    window.addEventListener('scroll', () => {
      setOffset(window.pageYOffset);
    });
  });

  return (

          <NavLinks  />

      </StyledWrapper>
    </StyledHeader>
  );
}

But its seems to be done in very inefficient way, because every scroll causes DOM rerender. Can this be done in some better way?

Body:
Try using a throttle or debounce function from lodash to limit the number of times your event handler function is executed. This way the event handler will only be executed at most every 200 milliseconds:

window.addEventListener('scroll', _.throttle(() => {
  setOffset(window.pageYOffset);
}, 200));

This is a good article that explains this idea in more detail and provides more examples: https://css-tricks.com/debouncing-throttling-explained-examples/


问:
Python Altair - Setting Minimum Bar Height for Interactive Graphs
I am currently generating an interactive stacked-bar graph, where individual stacks of the bar graph can be clicked on to update other graphics.

The issue I am running into is a problem of scale.  Sometimes, I will have a dataset where 1 bar has a reading of 25,000, and another will have a reading of 1.

It becomes near impossible to see, let alone click, that entry of 1, when the scale goes up so high due to another reading.

Is it possible to set a "minimum" height for any bar piece? I know this is likely difficult or weird due to Y-axis scaling then.

Thanks!

答:
There is no way to set a minimum bar height in Altair or Vega-Lite, short of modifying the input data which may be misleading.

Perhaps you could concatenate another chart with a shared axis, and provide interaction via that instead? for example:

```<code>import pandas as pd
import altair as alt

df = pd.DataFrame({
    'x': list('ABCDE'),
    'y': [1, 2, 3, 10000, 500]
})

selector = alt.selection_single(fields=['x'])
color = alt.condition(selector, alt.value('steelblue'), alt.value('lightgray'))

base = alt.Chart(df).mark_bar().encode(
    color=color
).add_selection(
    selector
)

bars = base.encode(
    x=alt.X('x:N', axis=None),
    y='y:Q',
)

rects = base.encode(
    x='x:N'
)

alt.vconcat(bars, rects).configure_concat(spacing=0)
</code>```

Body:
There is no way to set a minimum bar height in Altair or Vega-Lite, short of modifying the input data which may be misleading.

Perhaps you could concatenate another chart with a shared axis, and provide interaction via that instead? for example:

import pandas as pd
import altair as alt

df = pd.DataFrame({
    'x': list('ABCDE'),
    'y': [1, 2, 3, 10000, 500]
})

selector = alt.selection_single(fields=['x'])
color = alt.condition(selector, alt.value('steelblue'), alt.value('lightgray'))

base = alt.Chart(df).mark_bar().encode(
    color=color
).add_selection(
    selector
)

bars = base.encode(
    x=alt.X('x:N', axis=None),
    y='y:Q',
)

rects = base.encode(
    x='x:N'
)

alt.vconcat(bars, rects).configure_concat(spacing=0)


问:
TypeError: expect(...).toBeObservable is not a function - Jasmine marbles
I am trying to write a basic ngrx effects testing. However I keep getting the error as TypeError: expect(...).toBeObservable is not a function.

This is a new project setup with Angular 7. I had no issues with my previous projects which ran in angular 4.

Initially thought it could be something to do with packages so upgraded all packages to the most latest but no luck yet.

I event tried to test a very simple observable as expect(effects.test$).toBeObservable(5); but it gives the same error. As mentioned in the title I am using jasmine-marbles and the version is 0.4.1.

答:
You need to init the test scheduler and add matchers in before each or toBeObservable will not be defined:</p>

```<code>import { addMatchers, initTestScheduler } from 'jasmine-marbles';

beforeEach(() => {
  ...
  initTestScheduler();
  addMatchers();
});
</code>```

Body:
You need to init the test scheduler and add matchers in before each or toBeObservable will not be defined:

import { addMatchers, initTestScheduler } from 'jasmine-marbles';

beforeEach(() => {
  ...
  initTestScheduler();
  addMatchers();
});


问:
Liferay module listener : Unable to get who made a change to the model
I have to create custom auditing for the User model to track by whom the user has been deleted. I have tried to create a Liferay module listener for the User model, but I am not able to get the detail by whom the user is being deleted.

Is there any way to get details about who made a change to the User model in Liferay module listener?

My Liferay environment detail

Liferay portal : liferay-ce-portal-tomcat-7.0-ga5

Database : postgres (PostgreSQL) 9.5.17

IDE : eclipse-oxygen 4.7.3a

/*
 * Below is the sample code that I have tried to create the Liferay module listener for the User model
 */
package com.test.useraudit.modellistner;

import org.osgi.service.component.annotations.Component;

import com.liferay.portal.kernel.exception.ModelListenerException;
import com.liferay.portal.kernel.model.BaseModelListener;
import com.liferay.portal.kernel.model.ModelListener;
import com.liferay.portal.kernel.model.User;

@Component(
    immediate = true,
    service = ModelListener.class
)

public class CustomUserModelListner extends BaseModelListener<User>{
    @Override
    public void onBeforeRemove(User user) throws ModelListenerException{
        System.out.println("In onBeforeRemove method");
        System.out.println("User detail :");
        System.out.println(user);
        super.onBeforeRemove(user);
    }

    @Override
    public void onAfterRemove(User user) throws ModelListenerException{
        System.out.println("In onAfterRemove method");
        System.out.println("User detail :");
        System.out.println(user);
        super.onAfterRemove(user);
    }
}
```

答:
Yes it's possible.

There's an implicit thread local variable called ServiceContext that contains the calling context details.

Sample:

```<code>   @Override
    public void onBeforeRemove(User user) throws ModelListenerException{
            ServiceContext serviceContext =
                 ServiceContextThreadLocal.getServiceContext();

            System.out.println("Calling user:" + serviceContext.getUserId());
    }
</code>```

Body:
Yes it's possible.

There's an implicit thread local variable called ServiceContext that contains the calling context details.

Sample:

   @Override
    public void onBeforeRemove(User user) throws ModelListenerException{
            ServiceContext serviceContext =
                 ServiceContextThreadLocal.getServiceContext();

            System.out.println("Calling user:" + serviceContext.getUserId());
    }


答:
You can use a while loop:

```<code>ret = []
while len(exampleList) > 1:
    ret.append(exampleList)
    exampleList = reduce(exampleList)
ret.append(exampleList)
</code>```

Title: How to get successive random subsamples?

Body:
You can use a while loop:

ret = []
while len(exampleList) > 1:
    ret.append(exampleList)
    exampleList = reduce(exampleList)
ret.append(exampleList)


问:
Selenium Timed out receiving message from renderer
After Chrome released their newest version yesterday (64.0.3282), I am now receiving this error rather sporadically:

Timed out receiving message from renderer: 600.000

I'm running about 2,000 selenium tests within a docker container and I see this failure at a rate of about 1 in 100. There are no reproducible steps as far as I can tell- the tests that fail are different with each iteration. I updated to the newest Chromedriver (2.35), but that didn't seem to have any effect. I was previously using Selenium 2.41, but have updated to the newest version (3.8.1) hoping that it might help... it did not. I'm completely at a loss as to why this might be occurring. Has anyone else noticed this? Is it possibly a bug with Chrome's newest release?

Thank you in advance for any help you may be able to provide.

答:
In our case, we found the problem was a performance issue because the screenshot taken was huge but it happened because we realized the screenshot resolution of the screenshots created by Chrome was double than the specified in code for calling the chromedriver, for example, if we specified width 1024px and height 2000px in the screenshot, it was creating an image of 2048px width and 4000px height so that is why was taking too much for rendering and the timeout breaks the process, in cases when the process finished (after long wait) it was creating a heavy screenshot images. We found it was an option (problem) of Chrome for supporting retina devices which increase the resolution of the screenshot, so, we forced using a flag to deactivate the option and render the original resolution configured and it works well, taking between 8 seconds to 13 seconds to create the screenshot (depending on the content of the page) and the image size is less than at the begenning. This is the flag into the ChromeOptions object:</p>

```<code>options.addArguments("--force-device-scale-factor=1");
</code>```

Body:
In our case, we found the problem was a performance issue because the screenshot taken was huge but it happened because we realized the screenshot resolution of the screenshots created by Chrome was double than the specified in code for calling the chromedriver, for example, if we specified width 1024px and height 2000px in the screenshot, it was creating an image of 2048px width and 4000px height so that is why was taking too much for rendering and the timeout breaks the process, in cases when the process finished (after long wait) it was creating a heavy screenshot images. We found it was an option (problem) of Chrome for supporting retina devices which increase the resolution of the screenshot, so, we forced using a flag to deactivate the option and render the original resolution configured and it works well, taking between 8 seconds to 13 seconds to create the screenshot (depending on the content of the page) and the image size is less than at the begenning. This is the flag into the ChromeOptions object:

options.addArguments("--force-device-scale-factor=1");


问:
How to make a OptionMenu maintain the same width?
I have a snippet which creates an OptionMenu widget.

```<code>...
options = ('White', 'Grey', 'Black', 'Red', 'Orange',
           'Yellow', 'Green', 'Blue', 'Cyan', 'Purple')
var = StringVar()
optionmenu = OptionMenu(par, var, *options)
optionmenu.grid(column=column, row=row)
...
</code>```

One problem I've encountered is every time a new option is selected, the width of the widget changes. I believe this is due to the text within the widget changing widths. How do I make the widget hold a consistent width?

答:
To the best of my knowledge, you can use optionmenu.config(width=<YOUR_WIDTH>) as follows:

```<code>...
optionmenu = OptionMenu(par, var, *options)
optionmenu.config(width=<YOUR_WIDTH>)
optionmenu.grid(column=column, row=row)
...
</code>```

Body:
I have a snippet which creates an OptionMenu widget.

...
options = ('White', 'Grey', 'Black', 'Red', 'Orange',
           'Yellow', 'Green', 'Blue', 'Cyan', 'Purple')
var = StringVar()
optionmenu = OptionMenu(par, var, *options)
optionmenu.grid(column=column, row=row)
...

One problem I've encountered is every time a new option is selected, the width of the widget changes. I believe this is due to the text within the widget changing widths. How do I make the widget hold a consistent width?

Body:
To the best of my knowledge, you can use optionmenu.config(width=<YOUR_WIDTH>) as follows:

...
optionmenu = OptionMenu(par, var, *options)
optionmenu.config(width=<YOUR_WIDTH>)
optionmenu.grid(column=column, row=row)
...


问:
Rails: Installing font-awesome in Rails 6.0.0-rc1 with webpacker and yarn
I'm trying to install FontAwesome via yarn by doing yarn add @fontawesome/fontawesome-free, and then adding it to my application.scss:

```<code>$fa-font-path: '~@fortawesome/fontawesome-free-webfonts/webfonts';
@import '~@fortawesome/fontawesome-free-webfonts/scss/fontawesome';
@import '~@fortawesome/fontawesome-free-webfonts/scss/fa-solid';
</code>```

I have tried several things to write in the application.scss that I've seen through the internet, but none of them works, as I get the following error:

```<code>Sass::SyntaxError in Pages#index
Showing /Users/foo/dev/project/app/views/layouts/application.html.erb where line #9 raised:

File to import not found or unreadable: ~@fortawesome/fontawesome-free-webfonts/scss/fontawesome.
Load paths:
  /Users/foo/dev/project/app/assets/images
  /Users/foo/dev/project/app/assets/javascripts
  /Users/foo/dev/project/app/assets/stylesheets
  /Users/foo/dev/project/vendor/bundle/ruby/2.5.0/gems/coffee-rails-5.0.0/lib/assets/javascripts
  /Users/foo/dev/project/vendor/bundle/ruby/2.5.0/gems/actioncable-6.0.0.rc1/app/assets/javascripts
  /Users/foo/dev/project/vendor/bundle/ruby/2.5.0/gems/activestorage-6.0.0.rc1/app/assets/javascripts
  /Users/foo/dev/project/vendor/bundle/ruby/2.5.0/gems/actionview-6.0.0.rc1/lib/assets/compiled
  /Users/foo/dev/project/node_modules
</code>```

答:
Asim's answer put me on the right track. However, it seems like some of the import paths have changed for the newer version (5.8.2) of FontAwesome. Here is what I needed to put inside of my application.scss file to make FontAwesome 5.8.2 available for use in my Rails 6.0.0-rc1 application:

```<code>$fa-font-path: '~@fortawesome/fontawesome-free/webfonts';

@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/solid";
</code>```

Body:
I'm trying to install FontAwesome via yarn by doing yarn add @fontawesome/fontawesome-free, and then adding it to my application.scss:

$fa-font-path: '~@fortawesome/fontawesome-free-webfonts/webfonts';
@import '~@fortawesome/fontawesome-free-webfonts/scss/fontawesome';
@import '~@fortawesome/fontawesome-free-webfonts/scss/fa-solid';

I have tried several things to write in the application.scss that I've seen through the internet, but none of them works, as I get the following error:

Sass::SyntaxError in Pages#index
Showing /Users/foo/dev/project/app/views/layouts/application.html.erb where line #9 raised:

File to import not found or unreadable: ~@fortawesome/fontawesome-free-webfonts/scss/fontawesome.
Load paths:
  /Users/foo/dev/project/app/assets/images
  /Users/foo/dev/project/app/assets/javascripts
  /Users/foo/dev/project/app/assets/stylesheets
  /Users/foo/dev/project/vendor/bundle/ruby/2.5.0/gems/coffee-rails-5.0.0/lib/assets/javascripts
  /Users/foo/dev/project/vendor/bundle/ruby/2.5.0/gems/actioncable-6.0.0.rc1/app/assets/javascripts
  /Users/foo/dev/project/vendor/bundle/ruby/2.5.0/gems/activestorage-6.0.0.rc1/app/assets/javascripts
  /Users/foo/dev/project/vendor/bundle/ruby/2.5.0/gems/actionview-6.0.0.rc1/lib/assets/compiled
  /Users/foo/dev/project/node_modules

Body:
Asim's answer put me on the right track. However, it seems like some of the import paths have changed for the newer version (5.8.2) of FontAwesome. Here is what I needed to put inside of my application.scss file to make FontAwesome 5.8.2 available for use in my Rails 6.0.0-rc1 application:

$fa-font-path: '~@fortawesome/fontawesome-free/webfonts';

@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/solid";