问:
Spring boot ExceptionHandler when an exception is thrown within a service
I am using ControllerAdvice to handle exceptions in my spring boot application.

```<code>@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class ErrorApiHandler extends ResponseEntityExceptionHandler {

    final
    ResponsesHelper rh;

    public ErrorApiHandler(ResponsesHelper rh) {
        this.rh = rh;
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public ResponseEntity<Object> handleUsernameNotFoundException(UsernameNotFoundException ex) {
    log.error(ExceptionUtils.getStackTrace(ex));

    var error = buildError(ex);
    return rh.buildResponse(error, HttpStatus.NOT_FOUND);
    }
...
}
</code>```

It works fine for exceptions thrown within my controllers.
However, with exceptions thrown, for example within a service the ControllerAdvice is not executed.

```<code>@Service
public class CustomUserDetailsService implements UserDetailsService {

    final
    UserRepository userRepository;

    public CustomUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    @Transactional
    public User loadUserByUsername(String email)
            throws UsernameNotFoundException {

        log.debug(String.format("Loading user %s", email));

        User user = userRepository.findByEmail(email)
                .orElseThrow(() -> {

                    log.debug(String.format("User %s not found", email));
                    return new UsernameNotFoundException("User not found : " + email); // <- This exception is not handled.
                });

        log.debug(String.format("User %s loaded", user));
        return user;
    }
</code>```

How can I handle all exceptions thrown within my application?

Thanks in advance.

答:
In my case my "CustomUserDetailsService" is called inside a filter:

```<code>public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenProvider tokenProvider;

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
        ) throws ServletException, IOException {

        try {
            String jwt = getJwtFromRequest(request);

            if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
                UUID userId = tokenProvider.getUserIdFromJWT(jwt);

                UserDetails userDetails = customUserDetailsService.loadUserById(userId);
...
</code>```

I handled it by catching the exceptions there:

```<code>catch (UsernameNotFoundException ex){
            log.error(ExceptionUtils.getStackTrace(ex));

            var apiError = ErrorApiHandler.buildError(
                    new ResourceAlreadyTakenException(ex.getMessage())
            );

            response.addHeader("Content-Type", "application/json");
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            PrintWriter writer = response.getWriter();
            writer.write(convertObjectToJson(apiError));
            writer.flush();
            return;
        }
</code>```

Ideally, handle all exceptions with the controller advice, but this way it works

Body:
I am using ControllerAdvice to handle exceptions in my spring boot application.

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class ErrorApiHandler extends ResponseEntityExceptionHandler {

    final
    ResponsesHelper rh;

    public ErrorApiHandler(ResponsesHelper rh) {
        this.rh = rh;
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public ResponseEntity<Object> handleUsernameNotFoundException(UsernameNotFoundException ex) {
    log.error(ExceptionUtils.getStackTrace(ex));

    var error = buildError(ex);
    return rh.buildResponse(error, HttpStatus.NOT_FOUND);
    }
...
}

It works fine for exceptions thrown within my controllers.
However, with exceptions thrown, for example within a service the ControllerAdvice is not executed.

@Service
public class CustomUserDetailsService implements UserDetailsService {

    final
    UserRepository userRepository;

    public CustomUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    @Transactional
    public User loadUserByUsername(String email)
            throws UsernameNotFoundException {

        log.debug(String.format("Loading user %s", email));

        User user = userRepository.findByEmail(email)
                .orElseThrow(() -> {

                    log.debug(String.format("User %s not found", email));
                    return new UsernameNotFoundException("User not found : " + email); // <- This exception is not handled.
                });

        log.debug(String.format("User %s loaded", user));
        return user;
    }

How can I handle all exceptions thrown within my application?

Thanks in advance.

Body:
In my case my "CustomUserDetailsService" is called inside a filter:

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenProvider tokenProvider;

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
        ) throws ServletException, IOException {

        try {
            String jwt = getJwtFromRequest(request);

            if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
                UUID userId = tokenProvider.getUserIdFromJWT(jwt);

                UserDetails userDetails = customUserDetailsService.loadUserById(userId);
...

I handled it by catching the exceptions there:

catch (UsernameNotFoundException ex){
            log.error(ExceptionUtils.getStackTrace(ex));

            var apiError = ErrorApiHandler.buildError(
                    new ResourceAlreadyTakenException(ex.getMessage())
            );

            response.addHeader("Content-Type", "application/json");
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            PrintWriter writer = response.getWriter();
            writer.write(convertObjectToJson(apiError));
            writer.flush();
            return;
        }

Ideally, handle all exceptions with the controller advice, but this way it works


来源: stackexchange

问:
Animating the letters in a word w the app opens - SwiftUI
I'm trying to get a dancing letters effect when my app first opens.

I'm close. The coding below almost does what I want. I use a ForEach loop to loop through the letters of the word and apply an animation to each letter. And I use the onAppear function to set the drag amount when the app opens.

With this coding I can get the 'forward' motion but I can't get the animation to reverse so that the letters end up in their original position. I've tried adding a repeat with reverse, but, again, the letters never return to their original position

Does anyone have any idea how to do this?

```<code>struct ContentView: View {
  let letters = Array("Math Fun!")
  @State private var enabled = false
  @State private var dragAmount = CGSize.zero

  var body: some View {
    HStack(spacing: 0) {
      ForEach(0..<letters.count) { num in
        Text(String(self.letters[num]))
          .padding(5)
          .font(.title)
          .background(self.enabled ? Color.blue : Color.red)
          .offset(self.dragAmount)
          .animation(Animation.default.delay(Double(num)/20).repeatCount(3, autoreverses: true))
      }
    }
    .onAppear {
      self.dragAmount = CGSize(width: 0, height: 80)
      self.enabled.toggle()
    }
  }

}
</code>```

答:
Update: with Xcode 13.4 / iOS 15.5

Animation is based on changed states, we switched states and view animated to the new states, so to rollback we need to switch the states back.

Here is the possible approach (might still require tuning, but is ok for demo)

```<code>struct ContentView: View {
    let letters = Array("Math Fun!")
    @State private var enabled = false
    @State private var dragAmount = CGSize.zero

    var body: some View {
        HStack(spacing: 0) {
            ForEach(0..<letters.count, id: \.self) { num in
                Text(String(self.letters[num]))
                    .padding(5)
                    .font(.title)
                    .background(self.enabled ? Color.blue : Color.red)
                    .offset(self.dragAmount)
                    .animation(Animation.default.delay(Double(num)/20), value: enabled)
            }
        }
        .onAppear {
            self.dragAmount = CGSize(width: 0, height: 80)
            self.enabled.toggle()
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                self.dragAmount = .zero
                self.enabled.toggle()
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get a dancing letters effect when my app first opens.

I'm close. The coding below almost does what I want. I use a ForEach loop to loop through the letters of the word and apply an animation to each letter. And I use the onAppear function to set the drag amount when the app opens.

With this coding I can get the 'forward' motion but I can't get the animation to reverse so that the letters end up in their original position. I've tried adding a repeat with reverse, but, again, the letters never return to their original position

Does anyone have any idea how to do this?

struct ContentView: View {
  let letters = Array("Math Fun!")
  @State private var enabled = false
  @State private var dragAmount = CGSize.zero

  var body: some View {
    HStack(spacing: 0) {
      ForEach(0..<letters.count) { num in
        Text(String(self.letters[num]))
          .padding(5)
          .font(.title)
          .background(self.enabled ? Color.blue : Color.red)
          .offset(self.dragAmount)
          .animation(Animation.default.delay(Double(num)/20).repeatCount(3, autoreverses: true))
      }
    }
    .onAppear {
      self.dragAmount = CGSize(width: 0, height: 80)
      self.enabled.toggle()
    }
  }

}

Body:
Update: with Xcode 13.4 / iOS 15.5

Animation is based on changed states, we switched states and view animated to the new states, so to rollback we need to switch the states back.

Here is the possible approach (might still require tuning, but is ok for demo)

struct ContentView: View {
    let letters = Array("Math Fun!")
    @State private var enabled = false
    @State private var dragAmount = CGSize.zero

    var body: some View {
        HStack(spacing: 0) {
            ForEach(0..<letters.count, id: \.self) { num in
                Text(String(self.letters[num]))
                    .padding(5)
                    .font(.title)
                    .background(self.enabled ? Color.blue : Color.red)
                    .offset(self.dragAmount)
                    .animation(Animation.default.delay(Double(num)/20), value: enabled)
            }
        }
        .onAppear {
            self.dragAmount = CGSize(width: 0, height: 80)
            self.enabled.toggle()
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                self.dragAmount = .zero
                self.enabled.toggle()
            }
        }
    }
}


答:
Below is for BigQuery Standard SQL

```<code>#standardSQL
SELECT Stock1, Stock2, dt_date, zscore20,
  IFNULL(
    LAST_VALUE(flag IGNORE NULLS)
    OVER(PARTITION BY Stock1, Stock2 ORDER BY dt_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
  , 0) What_I_want
FROM (
  SELECT *,
    CASE
      WHEN zscore20 > 2.0 THEN -1
      WHEN zscore20 < -2.0 THEN 1
      WHEN zscore20 >= 0 AND prev_zscore20 < 0 THEN 0
      WHEN zscore20 < 0 AND prev_zscore20 >= 0 THEN 0
      ELSE NULL
    END flag
  FROM (
    SELECT Stock1, Stock2, dt_date, zscore20,
      LAG(zscore20) OVER(PARTITION BY Stock1, Stock2 ORDER BY dt_date) prev_zscore20
    FROM (
      SELECT *, PARSE_DATE('%d/%m/%Y', dt) dt_date
      FROM `project.dataset.table`
    )
  )
)
</code>```

You can test, play with above using sample data from your question as in below example

```<code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'FITB' Stock1, 'MS' Stock2, '4/01/2010' dt, -1.5 zscore20 UNION ALL
  SELECT 'FITB', 'MS', '5/01/2010', -1.9 UNION ALL
  SELECT 'FITB', 'MS', '6/01/2010', -2.3 UNION ALL
  SELECT 'FITB', 'MS', '7/01/2010', -2.0 UNION ALL
  SELECT 'FITB', 'MS', '8/01/2010', -1.0 UNION ALL
  SELECT 'FITB', 'MS', '11/01/2010', 0.5 UNION ALL
  SELECT 'FITB', 'MS', '12/01/2010', 1.5 UNION ALL
  SELECT 'FITB', 'MS', '13/01/2010', 1.8 UNION ALL
  SELECT 'FITB', 'MS', '14/01/2010', 2.1 UNION ALL
  SELECT 'FITB', 'MS', '15/01/2010', 1.5 UNION ALL
  SELECT 'FITB', 'MS', '19/01/2010', 1.3 UNION ALL
  SELECT 'FITB', 'MS', '20/01/2010', 0.4 UNION ALL
  SELECT 'FITB', 'MS', '21/01/2010', -0.1
)
SELECT Stock1, Stock2, dt_date, zscore20,
  IFNULL(
    LAST_VALUE(flag IGNORE NULLS)
    OVER(PARTITION BY Stock1, Stock2 ORDER BY dt_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
  , 0) What_I_want
FROM (
  SELECT *,
    CASE
      WHEN zscore20 > 2.0 THEN -1
      WHEN zscore20 < -2.0 THEN 1
      WHEN zscore20 >= 0 AND prev_zscore20 < 0 THEN 0
      WHEN zscore20 < 0 AND prev_zscore20 >= 0 THEN 0
      ELSE NULL
    END flag
  FROM (
    SELECT Stock1, Stock2, dt_date, zscore20,
      LAG(zscore20) OVER(PARTITION BY Stock1, Stock2 ORDER BY dt_date) prev_zscore20
    FROM (
      SELECT *, PARSE_DATE('%d/%m/%Y', dt) dt_date
      FROM `project.dataset.table`
    )
  )
)
-- ORDER BY dt_date
</code>```

with result

```<code>Row Stock1  Stock2  dt_date     zscore20    What_I_want
1   FITB    MS      2010-01-04  -1.5        0
2   FITB    MS      2010-01-05  -1.9        0
3   FITB    MS      2010-01-06  -2.3        1
4   FITB    MS      2010-01-07  -2.0        1
5   FITB    MS      2010-01-08  -1.0        1
6   FITB    MS      2010-01-11  0.5         0
7   FITB    MS      2010-01-12  1.5         0
8   FITB    MS      2010-01-13  1.8         0
9   FITB    MS      2010-01-14  2.1         -1
10  FITB    MS      2010-01-15  1.5         -1
11  FITB    MS      2010-01-19  1.3         -1
12  FITB    MS      2010-01-20  0.4         -1
13  FITB    MS      2010-01-21  -0.1        0
</code>```

Title: Testing Trade Entries in BigQuery/SQL

Body:
I have a data set in BigQuery of various pairs of stock prices, and their relative zscores (ordered by date, and in the millions of rows):

   +-----+--------+--------+------------+---------------+------------------+---------------+
1  | Row | stock1 | stock2 |    date    |  spreadclose  | logspreadreturn  |   zscore20    |
   +-----+--------+--------+------------+---------------+------------------+---------------+
2  | 1   | AJRD   | MAS    | 27/12/2010 |  0.537230704  |  0.017358199     | -0.251654379  |
3  | 2   | ABEV   | EFOI   | 27/12/2010 | 41.00585106   |  0.014929275     |  1.950810153  |
4  | 3   | AIRI   | REFR   | 27/12/2010 |  0.537688889  |  0.003638617     |  0.707555834  |
5  | 4   | AEO    | RJF    | 27/12/2010 |  0.35009565   | -0.004321474     |  0.265411543  |
6  | 5   | AFL    | TSU    | 27/12/2010 |  0.771122788  | -0.028202112     |  0.247268645  |
   +----+---------+--------+------------+---------------+------------------+---------------+

I then take a sample of the stock prices as per below. I am trying to calculate the trade entries as per the "What I want column" in Big query, but can only seem to achieve the numbers as per the "(Current(Wrong))" column.

   Stock1 Stock2     date       zscore20     (Current wrong)   What I want
1    FITB     MS  4/01/2010     -1.5               1           0
2    FITB     MS  5/01/2010     -1.9               1           0
3    FITB     MS  6/01/2010     -2.3               1           1
4    FITB     MS  7/01/2010     -2.0               1           1
5    FITB     MS  8/01/2010     -1.0               1           1
6    FITB     MS 11/01/2010      0.5              -1           0
7    FITB     MS 12/01/2010      1.5              -1           0
8    FITB     MS 13/01/2010      1.8              -1           0
9    FITB     MS 14/01/2010      2.1              -1          -1
10   FITB     MS 15/01/2010      1.5              -1          -1
11   FITB     MS 19/01/2010      1.3              -1          -1
12   FITB     MS 20/01/2010      0.4              -1          -1
13   FITB     MS 21/01/2010     -0.1               1           0

The logic in the "What I want column" is as follows:

In the time series, when zscore > 2.0, flag -1; then exit (0) when zscore next crosses zero into negative

In the time series, when zscore < -2.0, flag +1; then exit (0) when zscore next crosses zero into postitve

My current query that I run on the larger dataset (setting process year to 2010):

DECLARE processyear date;

SET processyear = '2012-01-01';

INSERT INTO `dataset.main.tradetime`(

-- Calculate tradetimeparameters
WITH tradetimeparameters AS (
SELECT
    stock1,
    stock2,
    date,
    spreadclose,
    LN(spreadclose) - LN(LAG(spreadclose) OVER (PARTITION BY stock1, stock2 ORDER BY date ASC)) as logspreadreturn,
    SAFE_DIVIDE((spreadclose - sma20), stdev20) as zscore20
FROM `rw-algotrader-264713.mlbprices.dailyspreads`
WHERE date >= DATE_SUB(processyear, INTERVAL 1 WEEK) and date < DATE_ADD(processyear, INTERVAL 1 YEAR)
),

secondtradetimeparameters AS (
SELECT
    stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    CASE WHEN zscore20 > 0 THEN -1 WHEN zscore20 < 0 THEN 1 END as tradesignal20
FROM tradetimeparameters
WHERE date >= DATE_SUB(processyear, INTERVAL 1 WEEK) and date < DATE_ADD(processyear, INTERVAL 1 YEAR)
),

thirdtradetimeparameters AS (
SELECT
    stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    LEAD(tradesignal20) OVER (PARTITION BY stock1, stock2 ORDER BY date ASC) as tradesignal20
FROM secondtradetimeparameters
WHERE date >= DATE_SUB(processyear, INTERVAL 1 WEEK) and date < DATE_ADD(processyear, INTERVAL 1 YEAR)
),

fourthtradetimeparameters AS (
SELECT
    stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    tradesignal20,
    CASE WHEN tradesignal20 < 0 THEN 0 ELSE tradesignal20 END as positivesignals,
    CASE WHEN tradesignal20 > 0 THEN 0 ELSE tradesignal20 END as negativesignals
FROM thirdtradetimeparameters
WHERE date >= DATE_SUB(processyear, INTERVAL 1 WEEK) and date < DATE_ADD(processyear, INTERVAL 1 YEAR)
),

fifthtradetimeparameters AS (
SELECT
    stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    tradesignal20,
    positivesignals,
    negativesignals,
       (case when positivesignals = 0 then 0
             else row_number() over (partition by stock1,stock2, positivesignals, grp order by date ASC)
        end) as positivedaysintrade
from (select stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    tradesignal20,
    positivesignals,
    negativesignals, countif(positivesignals = 0) over (partition by stock1,stock2 order by date ASC) as grp
      from fourthtradetimeparameters
     ) fourthtradetimeparameters
WHERE date >= DATE_SUB(processyear, INTERVAL 1 WEEK) and date < DATE_ADD(processyear, INTERVAL 1 YEAR)
),

sixthtradetimeparameters AS (
SELECT
    stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    tradesignal20,
    positivesignals,
    negativesignals,
    positivedaysintrade,
       (case when negativesignals = 0 then 0
             else row_number() over (partition by stock1,stock2, negativesignals, grp order by date ASC)
        end) as negativedaysintrade
from (select stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    tradesignal20,
    positivesignals,
    negativesignals,
    positivedaysintrade,countif(negativesignals = 0) over (partition by stock1,stock2 order by date ASC) as grp
      from fifthtradetimeparameters
     ) fifthtradetimeparameters
WHERE date >= DATE_SUB(processyear, INTERVAL 1 WEEK) and date < DATE_ADD(processyear, INTERVAL 1 YEAR)
),

seventhtradetimeparameters AS (
SELECT
    stock1,
    stock2,
    date,
    spreadclose,
    logspreadreturn,
    zscore20,
    tradesignal20,
    positivesignals,
    negativesignals,
    positivedaysintrade,
    negativedaysintrade,
    (positivedaysintrade + negativedaysintrade) as daysintrade,
    (tradesignal20 * logspreadreturn) as sdcreturn20

FROM sixthtradetimeparameters
WHERE date >= DATE_SUB(processyear, INTERVAL 1 WEEK) and date < DATE_ADD(processyear, INTERVAL 1 YEAR)
)

SELECT
  stock1,
  stock2,
  date,
  spreadclose,
  logspreadreturn,
  zscore20,
  tradesignal20,
  positivesignals,
  negativesignals,
  positivedaysintrade,
  negativedaysintrade,
  daysintrade,
  sdcreturn20
FROM seventhtradetimeparameters)

The second shorter table is as follows:

SELECT * FROM `dataset.tradetime` WHERE stock1 = 'FITB' and stock2 = 'MS' and date >= '2010-01-01'

Will appreciate if someone can guide me on the Bigquery/SQL code that can achieve the above. Many thanks in advance,

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT Stock1, Stock2, dt_date, zscore20,
  IFNULL(
    LAST_VALUE(flag IGNORE NULLS)
    OVER(PARTITION BY Stock1, Stock2 ORDER BY dt_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
  , 0) What_I_want
FROM (
  SELECT *,
    CASE
      WHEN zscore20 > 2.0 THEN -1
      WHEN zscore20 < -2.0 THEN 1
      WHEN zscore20 >= 0 AND prev_zscore20 < 0 THEN 0
      WHEN zscore20 < 0 AND prev_zscore20 >= 0 THEN 0
      ELSE NULL
    END flag
  FROM (
    SELECT Stock1, Stock2, dt_date, zscore20,
      LAG(zscore20) OVER(PARTITION BY Stock1, Stock2 ORDER BY dt_date) prev_zscore20
    FROM (
      SELECT *, PARSE_DATE('%d/%m/%Y', dt) dt_date
      FROM `project.dataset.table`
    )
  )
)

You can test, play with above using sample data from your question as in below example

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'FITB' Stock1, 'MS' Stock2, '4/01/2010' dt, -1.5 zscore20 UNION ALL
  SELECT 'FITB', 'MS', '5/01/2010', -1.9 UNION ALL
  SELECT 'FITB', 'MS', '6/01/2010', -2.3 UNION ALL
  SELECT 'FITB', 'MS', '7/01/2010', -2.0 UNION ALL
  SELECT 'FITB', 'MS', '8/01/2010', -1.0 UNION ALL
  SELECT 'FITB', 'MS', '11/01/2010', 0.5 UNION ALL
  SELECT 'FITB', 'MS', '12/01/2010', 1.5 UNION ALL
  SELECT 'FITB', 'MS', '13/01/2010', 1.8 UNION ALL
  SELECT 'FITB', 'MS', '14/01/2010', 2.1 UNION ALL
  SELECT 'FITB', 'MS', '15/01/2010', 1.5 UNION ALL
  SELECT 'FITB', 'MS', '19/01/2010', 1.3 UNION ALL
  SELECT 'FITB', 'MS', '20/01/2010', 0.4 UNION ALL
  SELECT 'FITB', 'MS', '21/01/2010', -0.1
)
SELECT Stock1, Stock2, dt_date, zscore20,
  IFNULL(
    LAST_VALUE(flag IGNORE NULLS)
    OVER(PARTITION BY Stock1, Stock2 ORDER BY dt_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
  , 0) What_I_want
FROM (
  SELECT *,
    CASE
      WHEN zscore20 > 2.0 THEN -1
      WHEN zscore20 < -2.0 THEN 1
      WHEN zscore20 >= 0 AND prev_zscore20 < 0 THEN 0
      WHEN zscore20 < 0 AND prev_zscore20 >= 0 THEN 0
      ELSE NULL
    END flag
  FROM (
    SELECT Stock1, Stock2, dt_date, zscore20,
      LAG(zscore20) OVER(PARTITION BY Stock1, Stock2 ORDER BY dt_date) prev_zscore20
    FROM (
      SELECT *, PARSE_DATE('%d/%m/%Y', dt) dt_date
      FROM `project.dataset.table`
    )
  )
)
-- ORDER BY dt_date

with result

Row Stock1  Stock2  dt_date     zscore20    What_I_want
1   FITB    MS      2010-01-04  -1.5        0
2   FITB    MS      2010-01-05  -1.9        0
3   FITB    MS      2010-01-06  -2.3        1
4   FITB    MS      2010-01-07  -2.0        1
5   FITB    MS      2010-01-08  -1.0        1
6   FITB    MS      2010-01-11  0.5         0
7   FITB    MS      2010-01-12  1.5         0
8   FITB    MS      2010-01-13  1.8         0
9   FITB    MS      2010-01-14  2.1         -1
10  FITB    MS      2010-01-15  1.5         -1
11  FITB    MS      2010-01-19  1.3         -1
12  FITB    MS      2010-01-20  0.4         -1
13  FITB    MS      2010-01-21  -0.1        0


问:
How can I compile c++ to multiple files?
I have a program (cpp) with many classes. Every class is in separate source file (.h + .cpp).

How can I split the compiled program into multiple files (instead of one big executable file)?

Let's say, one file for every class (same as the code structure).

So that every time there is change in a specific class, I compile only that class, and replace the specific compiled file related to that class.

(Something similar to .DLL files in Windows.)

Example from real life:

I am making TUI interface for managing mysql.

I would like to create mysql text editor (TUI) with ncurses.

the code (class) for creating and managing single window object is in
'textWin.cpp' + 'textWin.h'

the code (class) for managing multiple windows, by creating windows objects from previous class is in winMan.cpp winMan.h

the code (class) for managing mysql database is in :
mysql.cpp mysql.h

and so on...

so, I have the following files:

MyProgram.cpp

- winMan.cpp + winMan.h

- textWin.cpp + textWin.h

- mysql.cpp + mysql.h

- ..

- ..

After g++ compilation, I get one executable file, './MyProgram' (size about 15Mb.) which I deliver to all my customers (1000's of them).

I Just found a typo in textWin.cpp, I fixed it, and I told to all customers that there is an update... all of them need to download one big 15Mb file, this consumes allot of bandwidth and server resources, for just a small update.

Is there a way to send to all my customers smaller file, that contains only the compiled code for textWin class ?

I use g++ on Centos7

答:
The gcc compiler will happily take a list of cpp files to compile together to make one executable. You don't need to write a "containing" cpp file. However, you still have the issue that each time it rebuilds them all.

The alternative is to build each sourcefile separately to an object file, then link those all together. Hopefully each of those invocations of the compiler will add up to less time than the single command-line. But how to keep track of which cpp files actually need to be rebuilt?

The usual approach is to use a makefile and a make utility which will check the dates of all the mentioned files. There are a variety of flavours of makefile, and helper makefile engines. Download a simple package like gzip and you can quickly get an idea of how the Makefile is structured. Then there is lots of help online, or you may decide that this is just too much trouble for a project with 5 files in it.


问:
How to do RegAsm so that it cover 32-bit and 64-bit?
I have a DLL file prepared by C# and my system is Windows 7 64-bit.
When i apply the RegAsm its not adding the registry to 64-bit path but only adding it to 32-bit path.

```<code>"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe" /register /codebase "C:\o.dll"
</code>```

then if i check my GUID in regedit.exe i see that i have it only in 32-bit registry path: HKEY_CLASSES_ROOT\CLSID\{... my guid is found here ....}

instead of HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{... not found my guid ...}

As a result i have other issues for this. Can anyone please suggest what is going on and why its not making 32-bit and 64-bit registry entries?"

答:
On my 2016 windows server it was the opposite, it was an old dll that needed to be registered using the "Framework" folder, not the "Framework64" folder:
"C:\windows\Microsoft.net\Framework\v4.0.30319\regasm" /register /codebase "full path to dll here"</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a DLL file prepared by C# and my system is Windows 7 64-bit.
When i apply the RegAsm its not adding the registry to 64-bit path but only adding it to 32-bit path.

"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe" /register /codebase "C:\o.dll"

then if i check my GUID in regedit.exe i see that i have it only in 32-bit registry path: HKEY_CLASSES_ROOT\CLSID\{... my guid is found here ....}

instead of HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{... not found my guid ...}

As a result i have other issues for this. Can anyone please suggest what is going on and why its not making 32-bit and 64-bit registry entries?"


问:
Properly Handling Errors in VBA (Excel)
I've been working with VBA for quite a while now, but I'm still not so sure about Error Handling.

A good article is the one of
 CPearson.com

However I'm still wondering if the way I used to do ErrorHandling was/is completely wrong:
Block 1

```<code>On Error Goto ErrCatcher
   If UBound(.sortedDates) > 0 Then

       // Code

   Else
ErrCatcher:
       // Code

   End If
</code>```

The if clause, because if it is true, will be executed and if it fails the Goto will go into the Else-part, since the Ubound of an Array should never be zero or less, without an Error, this method worked quite well so far.

If I understood it right it should be like this:

Block 2

```<code>On Error Goto ErrCatcher
    If Ubound(.sortedDates) > 0 Then

       // Code
    End If

    Goto hereX

ErrCatcher:
       //Code
    Resume / Resume Next / Resume hereX

hereX:
</code>```

Or even like this:
Block 3

```<code>On Error Goto ErrCatcher
    If Ubound(.sortedDates) > 0 Then

       // Code
    End If

ErrCatcher:
    If Err.Number <> 0 then
       //Code
    End If
</code>```

The most common way I see is that one, that the Error "Catcher" is at the end of a sub and the Sub actually ends before with a "Exit Sub", but however isn't it a little confusing if the Sub is quite big if you jump vice versa to read through the code?

Block 4

Source of the following Code:
   CPearson.com

```<code>  On Error Goto ErrHandler:
   N = 1 / 0    ' cause an error
   '
   ' more code
   '
  Exit Sub

  ErrHandler:

   ' error handling code'

   Resume Next

End Sub
</code>```

Should it be like in Block 3 ?

答:
I definitely wouldn't use Block1. It doesn't seem right having the Error block in an IF statement unrelated to Errors.

Blocks 2,3 & 4 I guess are variations of a theme. I prefer the use of Blocks 3 & 4 over 2 only because of a dislike of the GOTO statement; I generally use the Block4 method. This is one example of code I use to check if the Microsoft ActiveX Data Objects 2.8 Library is added and if not add or use an earlier version if 2.8 is not available.

```<code>Option Explicit
Public booRefAdded As Boolean 'one time check for references

Public Sub Add_References()
Dim lngDLLmsadoFIND As Long

If Not booRefAdded Then
    lngDLLmsadoFIND = 28 ' load msado28.tlb, if cannot find step down versions until found

        On Error GoTo RefErr:
            'Add Microsoft ActiveX Data Objects 2.8
            Application.VBE.ActiveVBProject.references.AddFromFile _
            Environ("CommonProgramFiles") + "\System\ado\msado" & lngDLLmsadoFIND & ".tlb"

        On Error GoTo 0

    Exit Sub

RefErr:
        Select Case Err.Number
            Case 0
                'no error
            Case 1004
                 'Enable Trust Centre Settings
                 MsgBox ("Certain VBA References are not available, to allow access follow these steps" & Chr(10) & _
                 "Goto Excel Options/Trust Centre/Trust Centre Security/Macro Settings" & Chr(10) & _
                 "1. Tick - 'Disable all macros with notification'" & Chr(10) & _
                 "2. Tick - 'Trust access to the VBA project objects model'")
                 End
            Case 32813
                 'Err.Number 32813 means reference already added
            Case 48
                 'Reference doesn't exist
                 If lngDLLmsadoFIND = 0 Then
                    MsgBox ("Cannot Find Required Reference")
                    End
                Else
                    For lngDLLmsadoFIND = lngDLLmsadoFIND - 1 To 0 Step -1
                           Resume
                    Next lngDLLmsadoFIND
                End If

            Case Else
                 MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
                End
        End Select

        On Error GoTo 0
End If
booRefAdded = TRUE
End Sub
</code>```

Title: Properly Handling Errors in VBA (Excel)

Body:
I've been working with VBA for quite a while now, but I'm still not so sure about Error Handling.

A good article is the one of
 CPearson.com

However I'm still wondering if the way I used to do ErrorHandling was/is completely wrong:
Block 1

On Error Goto ErrCatcher
   If UBound(.sortedDates) > 0 Then

       // Code

   Else
ErrCatcher:
       // Code

   End If

The if clause, because if it is true, will be executed and if it fails the Goto will go into the Else-part, since the Ubound of an Array should never be zero or less, without an Error, this method worked quite well so far.

If I understood it right it should be like this:

Block 2

On Error Goto ErrCatcher
    If Ubound(.sortedDates) > 0 Then

       // Code
    End If

    Goto hereX

ErrCatcher:
       //Code
    Resume / Resume Next / Resume hereX

hereX:

Or even like this:
Block 3

On Error Goto ErrCatcher
    If Ubound(.sortedDates) > 0 Then

       // Code
    End If

ErrCatcher:
    If Err.Number <> 0 then
       //Code
    End If

The most common way I see is that one, that the Error "Catcher" is at the end of a sub and the Sub actually ends before with a "Exit Sub", but however isn't it a little confusing if the Sub is quite big if you jump vice versa to read through the code?

Block 4

Source of the following Code:
   CPearson.com

  On Error Goto ErrHandler:
   N = 1 / 0    ' cause an error
   '
   ' more code
   '
  Exit Sub

  ErrHandler:

   ' error handling code'

   Resume Next

End Sub

Should it be like in Block 3 ?

Body:
I definitely wouldn't use Block1. It doesn't seem right having the Error block in an IF statement unrelated to Errors.

Blocks 2,3 & 4 I guess are variations of a theme. I prefer the use of Blocks 3 & 4 over 2 only because of a dislike of the GOTO statement; I generally use the Block4 method. This is one example of code I use to check if the Microsoft ActiveX Data Objects 2.8 Library is added and if not add or use an earlier version if 2.8 is not available.

Option Explicit
Public booRefAdded As Boolean 'one time check for references

Public Sub Add_References()
Dim lngDLLmsadoFIND As Long

If Not booRefAdded Then
    lngDLLmsadoFIND = 28 ' load msado28.tlb, if cannot find step down versions until found

        On Error GoTo RefErr:
            'Add Microsoft ActiveX Data Objects 2.8
            Application.VBE.ActiveVBProject.references.AddFromFile _
            Environ("CommonProgramFiles") + "\System\ado\msado" & lngDLLmsadoFIND & ".tlb"

        On Error GoTo 0

    Exit Sub

RefErr:
        Select Case Err.Number
            Case 0
                'no error
            Case 1004
                 'Enable Trust Centre Settings
                 MsgBox ("Certain VBA References are not available, to allow access follow these steps" & Chr(10) & _
                 "Goto Excel Options/Trust Centre/Trust Centre Security/Macro Settings" & Chr(10) & _
                 "1. Tick - 'Disable all macros with notification'" & Chr(10) & _
                 "2. Tick - 'Trust access to the VBA project objects model'")
                 End
            Case 32813
                 'Err.Number 32813 means reference already added
            Case 48
                 'Reference doesn't exist
                 If lngDLLmsadoFIND = 0 Then
                    MsgBox ("Cannot Find Required Reference")
                    End
                Else
                    For lngDLLmsadoFIND = lngDLLmsadoFIND - 1 To 0 Step -1
                           Resume
                    Next lngDLLmsadoFIND
                End If

            Case Else
                 MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
                End
        End Select

        On Error GoTo 0
End If
booRefAdded = TRUE
End Sub


问:
SPARQL: array-strings conversion / extraction
I am doing a SPARQL Query that for one variable gives me the output "[-1.6101874126499998e-19]". This is obviously a string containing an array (that could also contain more numbers). Is there a way to access the number in it or does it need to be done in the underlying graph?

If it needs to be changed in the graph, what is a good ontological way to create multi-dimensional arrays...?

答: xsd:float(SUBSTR(?var,2,STRLEN(?var)-2)) does the job in this case, but it's quite hacky :/


问:
inserting and bolding a string in microsoft vba code
Here is a snippet from code that I have created. It is working at the moment, but now I need to format the document. I am trying to make the third line in this code create an output that is bold, but I am stuck on how to do it.

Snippet of code I am trying to edit:

```<code>    ActiveDocument.Content.InsertAfter (MyArray(iRow, 7))
    ActiveDocument.Content.InsertAfter (MyArray(iRow, 8))
    ActiveDocument.Content.InsertAfter "Correct Answer is: " & (MyArray(iRow, 9))
    ActiveDocument.Content.InsertAfter (MyArray(iRow, 10))
    ActiveDocument.Content.InsertAfter (MyArray(iRow, 11))
    ActiveDocument.Content.InsertAfter (MyArray(iRow, 12))
</code>```

Here is the initial set up in the code in case you are wondering how the variables are set up:

```<code>Dim objWord
Dim ObjNewDoc As Document

Dim RowsCount As Integer
Dim ColsCount As Integer

Dim rngFormat As Range

Dim MyArray() As String

Dim iRow As Integer
Dim iCol As Integer
</code>```

I am trying to make the third line's output bold while leaving the remainder not bold. However, I am keep getting errors in VBA and am unsure how to overcome them.

On the Microsoft VBA reference website, it says the syntax is, "expression.Bold". I tried to insert it and it created an error obviously.

答:
There are numerous ways this can be approached - no one of them is "right" or "wrong" (assuming it works); what is used is a matter of preference. In any case, it's best solved working with one (or more) specific Range objects.

I prefer to work with a Range target, rather than using InsertAfter as I feel it gives me more control. Instead of InsertAfter I Collapse the Range object to its end-point. Think of it like pressing right-arrow to "collapse" a selection to a point.

This is done whenever the content needs to be handled differently. As long as strings are being written, they can all be inserted in one "line of code", as in the below example. When something needs to be done differently, the Range is collapsed and processing continues. This is done each time something needs to be different.

```<code>Sub InsertAndFormatContent
  Dim rng as Range
  Dim MyArray() As String
  Dim objNewDoc as Document

  'Populate MyArray here
  Set objNewDoc = Documents.Add()
  Set rng = objNewDoc.Content

  ' This code cannot run as MyArray is not populated!!!
  rng.Text = (MyArray(iRow, 7)) & (MyArray(iRow, 8)) & (MyArray(iRow, 9))
  rng.Collapse wdCollapseEnd
  rng.Text = "Correct answer is: " & (MyArray(iRow, 9))
  rng.Font.Bold = True
  rng.Collapse wdCollapseEnd
  rng.Text = (MyArray(iRow, 10)) & (MyArray(iRow,1)) & (MyArray(iRow, 12))
End Sub
</code>```

Body:
Here is a snippet from code that I have created. It is working at the moment, but now I need to format the document. I am trying to make the third line in this code create an output that is bold, but I am stuck on how to do it.

Snippet of code I am trying to edit:

    ActiveDocument.Content.InsertAfter (MyArray(iRow, 7))
    ActiveDocument.Content.InsertAfter (MyArray(iRow, 8))
    ActiveDocument.Content.InsertAfter "Correct Answer is: " & (MyArray(iRow, 9))
    ActiveDocument.Content.InsertAfter (MyArray(iRow, 10))
    ActiveDocument.Content.InsertAfter (MyArray(iRow, 11))
    ActiveDocument.Content.InsertAfter (MyArray(iRow, 12))

Here is the initial set up in the code in case you are wondering how the variables are set up:

Dim objWord
Dim ObjNewDoc As Document

Dim RowsCount As Integer
Dim ColsCount As Integer

Dim rngFormat As Range

Dim MyArray() As String

Dim iRow As Integer
Dim iCol As Integer

I am trying to make the third line's output bold while leaving the remainder not bold. However, I am keep getting errors in VBA and am unsure how to overcome them.

On the Microsoft VBA reference website, it says the syntax is, "expression.Bold". I tried to insert it and it created an error obviously.

Body:
There are numerous ways this can be approached - no one of them is "right" or "wrong" (assuming it works); what is used is a matter of preference. In any case, it's best solved working with one (or more) specific Range objects.

I prefer to work with a Range target, rather than using InsertAfter as I feel it gives me more control. Instead of InsertAfter I Collapse the Range object to its end-point. Think of it like pressing right-arrow to "collapse" a selection to a point.

This is done whenever the content needs to be handled differently. As long as strings are being written, they can all be inserted in one "line of code", as in the below example. When something needs to be done differently, the Range is collapsed and processing continues. This is done each time something needs to be different.

Sub InsertAndFormatContent
  Dim rng as Range
  Dim MyArray() As String
  Dim objNewDoc as Document

  'Populate MyArray here
  Set objNewDoc = Documents.Add()
  Set rng = objNewDoc.Content

  ' This code cannot run as MyArray is not populated!!!
  rng.Text = (MyArray(iRow, 7)) & (MyArray(iRow, 8)) & (MyArray(iRow, 9))
  rng.Collapse wdCollapseEnd
  rng.Text = "Correct answer is: " & (MyArray(iRow, 9))
  rng.Font.Bold = True
  rng.Collapse wdCollapseEnd
  rng.Text = (MyArray(iRow, 10)) & (MyArray(iRow,1)) & (MyArray(iRow, 12))
End Sub


问:
Matlab change in symbolic notation of derivative
I've recently upgraded Matlab from 2013b to 2019a (yes, I know, a lot has changed....but not software costs). I have some "legacy code" which makes heavy use of the symbolic tool box. One thing that seems to be causing a big issue is the change in notation. I think this question is best presented through example:

2013

```<code>>> F(x) = sym('F(x)');
>> subs(diff(F,x),x,1)

ans(x) =

D(F)(1)
</code>```

2019

```<code>>> F(x) = str2sym('F(x)');
>> subs(diff(F,x),x,1)

ans(x) =

subs(diff(F(x), x), x, 1)
</code>```

In 2019, F(x) = sym('F(x)'); would not work and I was told to switch to F(x) = str2sym('F(x)'); which seems to perform the operation as intended, but the notation is killing my code.

Is there a way to salvage the old notation or do I have to rewrite my code?

EDIT

Good comment.....how is this breaking my code? I use the symbolic tools to solve equations then parse them based on their structure. For example, if an expression has a third derivative, I would put that in group A. If it has a 7 derivative, I would put that in group B. In 2013, it was easy to parse for high derivatives...a third derivative would look like this D(D(D(F)))(x) in 2019 it looks like this diff(F(x), x, x, x). I've also found that 2019 mixes its notation. For example

```<code>F(x) = str2sym('F(x+dx)')
F(x) =

F(dx + x)

>> diff(F,x,3)

ans(x) =

D(D(D(F)))(dx + x)
</code>```

At this point, I'm thinking this is just going to end up being one patch fix after another. Probably not the best idea to be parsing symbolic expressions if the notation is volatile. I was hoping there might be a "yeah, go to preferences and select..."

答:
(requries MATLAB 2019a or later)

Not an answer on how to restore the old syntax, but to the problem you described. Here is how I would solve it:

```<code>%some example input
syms x f(x)
g=diff(f,x,3)+8
%find the expression with `diff` and get its arguments
a=children(findSymType(g,'diff'))
</code>```

This will return [ f(x), x, x, x], which means all you have to do is to throw away the first element and count the x

Body:
I've recently upgraded Matlab from 2013b to 2019a (yes, I know, a lot has changed....but not software costs). I have some "legacy code" which makes heavy use of the symbolic tool box. One thing that seems to be causing a big issue is the change in notation. I think this question is best presented through example:

2013

>> F(x) = sym('F(x)');
>> subs(diff(F,x),x,1)

ans(x) =

D(F)(1)

2019

>> F(x) = str2sym('F(x)');
>> subs(diff(F,x),x,1)

ans(x) =

subs(diff(F(x), x), x, 1)

In 2019, F(x) = sym('F(x)'); would not work and I was told to switch to F(x) = str2sym('F(x)'); which seems to perform the operation as intended, but the notation is killing my code.

Is there a way to salvage the old notation or do I have to rewrite my code?

EDIT

Good comment.....how is this breaking my code? I use the symbolic tools to solve equations then parse them based on their structure. For example, if an expression has a third derivative, I would put that in group A. If it has a 7 derivative, I would put that in group B. In 2013, it was easy to parse for high derivatives...a third derivative would look like this D(D(D(F)))(x) in 2019 it looks like this diff(F(x), x, x, x). I've also found that 2019 mixes its notation. For example

F(x) = str2sym('F(x+dx)')
F(x) =

F(dx + x)

>> diff(F,x,3)

ans(x) =

D(D(D(F)))(dx + x)

At this point, I'm thinking this is just going to end up being one patch fix after another. Probably not the best idea to be parsing symbolic expressions if the notation is volatile. I was hoping there might be a "yeah, go to preferences and select..."

Body:
(requries MATLAB 2019a or later)

Not an answer on how to restore the old syntax, but to the problem you described. Here is how I would solve it:

%some example input
syms x f(x)
g=diff(f,x,3)+8
%find the expression with `diff` and get its arguments
a=children(findSymType(g,'diff'))

This will return [ f(x), x, x, x], which means all you have to do is to throw away the first element and count the x


问:
How to get overlay to position on an image?
I am making a document in a grid format and when I hover over the image I want to have an overlay, it randomly goes underneath it.  How would I bring this effect higher up on the document. (The first image in the only one with the effect currently). HTML won't display in a code block here for some reason so I attached my codepen, thank you everyone!

```<code>.flex {
  display: grid;
  grid-gap: 2rem;
  grid-template-columns: repeat(3, 1fr);
  margin: 0% 5% 5% 5%;
}
.resize {
  max-width: 100%;
}
.overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: cyan;
  overflow: hidden;
  width: 28%;
  height: 0;
  transition: .5s ease;
  opacity: 0.3;
   margin: 0% 0% 0% 5%;
}

.contained1:hover .overlay {
  height: 35%;
  width: 28%;
  margin: 0% 0% 0% 5%;
}

.text {
  color: white;
  font-size: 20px;
  position: absolute;
  top: 90%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  font-family: 'karla';
}
</code>```

CODE PEN: https://codepen.io/daniel-albano/pen/vYOKRzp?editors=1100

答:
If i understood you correctly the easiest way is to make it absolute relative to parent. In this example the .contained1 had to have postion: relative; and make it invisible while not hovering.

```<code>.contained1 {
  position: relative;
  overflow: hidden;
}
.overlay {
  position: absolute;
  top: 0;
  left: 0;
  background-color: #2a7de1;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: .5s ease;
  opacity: 0.7;
  transform: translate(100%, 100%);
}

.contained1:hover .overlay {
  transform: translate(0, 0);
}
</code>```

So the way i done it is to make parent overflow: hidden then overlay need to go outside to make it invisbile by doing transform: translate(100%, 100%); (you dont really need to do it on x and y axis simultaneously). Then while user hovers on it you just reset transform: translate(0, 0); to its initial value and that's it

I hope i have resolved your problem ❤

Body:
I am making a document in a grid format and when I hover over the image I want to have an overlay, it randomly goes underneath it.  How would I bring this effect higher up on the document. (The first image in the only one with the effect currently). HTML won't display in a code block here for some reason so I attached my codepen, thank you everyone!

.flex {
  display: grid;
  grid-gap: 2rem;
  grid-template-columns: repeat(3, 1fr);
  margin: 0% 5% 5% 5%;
}
.resize {
  max-width: 100%;
}
.overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: cyan;
  overflow: hidden;
  width: 28%;
  height: 0;
  transition: .5s ease;
  opacity: 0.3;
   margin: 0% 0% 0% 5%;
}

.contained1:hover .overlay {
  height: 35%;
  width: 28%;
  margin: 0% 0% 0% 5%;
}

.text {
  color: white;
  font-size: 20px;
  position: absolute;
  top: 90%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  font-family: 'karla';
}

CODE PEN: https://codepen.io/daniel-albano/pen/vYOKRzp?editors=1100

Body:
If i understood you correctly the easiest way is to make it absolute relative to parent. In this example the .contained1 had to have postion: relative; and make it invisible while not hovering.

.contained1 {
  position: relative;
  overflow: hidden;
}
.overlay {
  position: absolute;
  top: 0;
  left: 0;
  background-color: #2a7de1;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: .5s ease;
  opacity: 0.7;
  transform: translate(100%, 100%);
}

.contained1:hover .overlay {
  transform: translate(0, 0);
}

So the way i done it is to make parent overflow: hidden then overlay need to go outside to make it invisbile by doing transform: translate(100%, 100%); (you dont really need to do it on x and y axis simultaneously). Then while user hovers on it you just reset transform: translate(0, 0); to its initial value and that's it

I hope i have resolved your problem ❤


问:
Make side bars reducing with max-width by degrees
How to make side parts of web page reduce they width with reducing width of whole page by degrees?

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .container {
            display: grid;
            grid-template-columns: 10% 80% 10%;
            min-height: 100vh;
        }
        .side-right {
            background: red;
        }
        .side-left {
            background: blue;
        }
        .main {
            background: green;
        }
        @media screen and (max-width: 1000px) {
            .container {
                grid-template-columns: 0 100% 0;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="side-right">
    </div>
    <div class="main">
    </div>
    <div class="side-left">
    </div>
</div>
</body>
</html>
</code>```

In example below after max-width = 1000px side elements are dissapearing instantly, but I want to make them reducing they width reacting by every pixel changed on max-width. How to make it?

答:
Try to add min-with: 50px; to .side-right and .side-left
And then give them both an z-index: 1;
So they wont lay under your main

Hope that helps

Body:
How to make side parts of web page reduce they width with reducing width of whole page by degrees?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

In example below after max-width = 1000px side elements are dissapearing instantly, but I want to make them reducing they width reacting by every pixel changed on max-width. How to make it?


问:
WPF style not applied at runtime
I am trying to apply a Style on a CheckBox. The problem is: the Style is applied at design-time, but not at run-time. It's working only if I'm putting the Style in MainWindow.xaml.

I have a Style in a resource dictionary. Here it is, in App.xaml:

```<code><Application.Resources>
  <ResourceDictionary>
    <Style x:Key="ToggleButton" TargetType="{x:Type CheckBox}">
      <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}"/>
      <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type CheckBox}">
            <ControlTemplate.Resources>
              <Storyboard x:Key="OnChecking">
                <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="slider" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)">
                  <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="25"/>
                </DoubleAnimationUsingKeyFrames>
              </Storyboard>
              <Storyboard x:Key="OnUnchecking">
                <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="slider" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)">
                  <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="0"/>
                </DoubleAnimationUsingKeyFrames>
                <ThicknessAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="slider" Storyboard.TargetProperty="(FrameworkElement.Margin)">
                  <SplineThicknessKeyFrame KeyTime="00:00:00.3000000" Value="1,1,1,1"/>
                </ThicknessAnimationUsingKeyFrames>
              </Storyboard>
            </ControlTemplate.Resources>

            <DockPanel x:Name="dockPanel">
              <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" ContentTemplate="{TemplateBinding ContentTemplate}" RecognizesAccessKey="True" VerticalAlignment="Center"/>
              <Grid Margin="5,5,0,5" Width="50" Background="#FFC0CCD9">
                <TextBlock Text="ON" TextWrapping="Wrap" FontWeight="Bold" FontSize="12" HorizontalAlignment="Right" Margin="0,0,3,0"/>
                <TextBlock HorizontalAlignment="Left" Margin="2,0,0,0" FontSize="12" FontWeight="Bold" Text="OFF" TextWrapping="Wrap"/>
                <Border HorizontalAlignment="Left" x:Name="slider" Width="23" BorderThickness="1,1,1,1" CornerRadius="3,3,3,3" RenderTransformOrigin="0.5,0.5" Margin="1,1,1,1">
                  <Border.RenderTransform>
                    <TransformGroup>
                      <ScaleTransform ScaleX="1" ScaleY="1"/>
                      <SkewTransform AngleX="0" AngleY="0"/>
                      <RotateTransform Angle="0"/>
                      <TranslateTransform X="0" Y="0"/>
                    </TransformGroup>
                  </Border.RenderTransform>
                  <Border.BorderBrush>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                      <GradientStop Color="#FFFFFFFF" Offset="0"/>
                      <GradientStop Color="#FF4490FF" Offset="1"/>
                    </LinearGradientBrush>
                  </Border.BorderBrush>
                  <Border.Background>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                      <GradientStop Color="#FF8AB4FF" Offset="1"/>
                      <GradientStop Color="#FFD1E2FF" Offset="0"/>
                    </LinearGradientBrush>
                  </Border.Background>
                </Border>
              </Grid>
            </DockPanel>

            <ControlTemplate.Triggers>
              <Trigger Property="IsChecked" Value="True">
                <Trigger.ExitActions>
                  <BeginStoryboard Storyboard="{StaticResource OnUnchecking}" x:Name="OnUnchecking_BeginStoryboard"/>
                </Trigger.ExitActions>
                <Trigger.EnterActions>
                  <BeginStoryboard Storyboard="{StaticResource OnChecking}" x:Name="OnChecking_BeginStoryboard"/>
                </Trigger.EnterActions>
              </Trigger>
              <Trigger Property="IsEnabled" Value="False">
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
              </Trigger>
            </ControlTemplate.Triggers>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </ResourceDictionary>
</Application.Resources>
</code>```

This is how I am trying to apply style:

```<code><CheckBox HorizontalAlignment="Center" Style="{DynamicResource ToggleButton}" VerticalAlignment="Center" Content="Test"/>
</code>```

UPDATE:
I found out that the Style is not applying at run-time when my startup location is not App, but the class Program.cs that I created.

答:
I have seen this occur when the style TargetType is for a base class, not the specific derived class. In this situation the designer showed me the style applied as it was intended, but at runtime it was not.

I was using VS2015 designer in particular.

I eventually resolved this by following advice in Applying a style to all derived classes in WPF and How to make a WPF style inheritable to derived classes?.

Title: WPF style not applied at runtime

Body:
I am trying to apply a Style on a CheckBox. The problem is: the Style is applied at design-time, but not at run-time. It's working only if I'm putting the Style in MainWindow.xaml.

I have a Style in a resource dictionary. Here it is, in App.xaml:

<Application.Resources>
  <ResourceDictionary>

  </ResourceDictionary>
</Application.Resources>

This is how I am trying to apply style:

<CheckBox HorizontalAlignment="Center" Style="{DynamicResource ToggleButton}" VerticalAlignment="Center" Content="Test"/>

UPDATE:
I found out that the Style is not applying at run-time when my startup location is not App, but the class Program.cs that I created.


问:
Django WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:3022]
i want to create chat app, i follow the https://channels.readthedocs.io/en/latest/tutorial/part_2.html here,

```<code>chat/
    __init__.py
    routing.py
    urls.py
    settings.py
    wsgi.py
</code>```

i added this code to my routing.py

```<code>from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})
</code>```

in my settings.py

```<code>ASGI_APPLICATION = 'Accounting.routing.application'
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}
</code>```

in my urls.py

```<code>urlpatterns = [
    path('chat/', include('chat.urls')),
    path('admin/', admin.site.urls),
]
</code>```

in my chat app

```<code>chat/
    __init__.py
    consumers.py
    routing.py
    templates/
        chat/
            index.html
            room.html
    urls.py
    views.py
</code>```

i have consumers.py

```<code>from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
import json

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        }))
</code>```

this is the code in my chat>routing.py

```<code>from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer),
]
</code>```

in my chat>views.py

```<code>from django.shortcuts import render

def index(request):
    return render(request, 'chat/index.html', {})

def room(request, room_name):
    return render(request, 'chat/room.html', {
        'room_name': room_name
    })
</code>```

i have urls.py in my chat app

from django.urls import path

```<code>from . import views
app_name = 'chat'
urlpatterns = [
    path('', views.index, name='index'),
    path('<str:room_name>/', views.room, name='room'),
]
</code>```

i follow all the direction, i copy paste the code, the placement of py, everything in the turorial, but still i get this error

did i miss something?

UPDATE

when i tried this in my pycharm terminal
docker run -p 6379:6379 -d redis:2.8

答:
a few things have issues here.

1) you are mixing async and sync consumer code.

I suggest just using the async consumer all you methods then should be async methods.

It looks like you are calling get_thread from a sync context but get_thread has been wrapped in database_sync_to_async so needs to be Called from an async context (and needs to be awaited).

you also need to await self.channel_layer.group_add

2) in your ThreadView you have a ChatMessage.objects.create here you should also send a message over the thread channel group.

from channels.layers import get_channel_layer
channel_layer = get_channel_layer()

async_to_sync(channel_layer.group_send)(f"thread_{thread.id}", {"type": "chat.message", "text": ...})
```

you also need to save the Chat message to the DB in your websocket_receive.

Body:
i want to create chat app, i follow the https://channels.readthedocs.io/en/latest/tutorial/part_2.html here,

chat/
    __init__.py
    routing.py
    urls.py
    settings.py
    wsgi.py

i added this code to my routing.py

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})

in my settings.py

ASGI_APPLICATION = 'Accounting.routing.application'
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}

in my urls.py

urlpatterns = [
    path('chat/', include('chat.urls')),
    path('admin/', admin.site.urls),
]

in my chat app

chat/
    __init__.py
    consumers.py
    routing.py
    templates/
        chat/
            index.html
            room.html
    urls.py
    views.py

i have consumers.py

from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
import json

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        }))

this is the code in my chat>routing.py

from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer),
]

in my chat>views.py

from django.shortcuts import render

def index(request):
    return render(request, 'chat/index.html', {})

def room(request, room_name):
    return render(request, 'chat/room.html', {
        'room_name': room_name
    })

i have urls.py in my chat app

from django.urls import path

from . import views
app_name = 'chat'
urlpatterns = [
    path('', views.index, name='index'),
    path('<str:room_name>/', views.room, name='room'),
]

i follow all the direction, i copy paste the code, the placement of py, everything in the turorial, but still i get this error

did i miss something?

UPDATE

when i tried this in my pycharm terminal
docker run -p 6379:6379 -d redis:2.8

Body:
a few things have issues here.

1) you are mixing async and sync consumer code.

I suggest just using the async consumer all you methods then should be async methods.

It looks like you are calling get_thread from a sync context but get_thread has been wrapped in database_sync_to_async so needs to be Called from an async context (and needs to be awaited).

you also need to await self.channel_layer.group_add

2) in your ThreadView you have a ChatMessage.objects.create here you should also send a message over the thread channel group.

from channels.layers import get_channel_layer
channel_layer = get_channel_layer()

async_to_sync(channel_layer.group_send)(f"thread_{thread.id}", {"type": "chat.message", "text": ...})

you also need to save the Chat message to the DB in your websocket_receive.


问:
How to insert values to a nested array
I am having one report array of objects which is used to show report data on the dashboard as below,

```<code>    report = [
              {id: "id01", code: "C001", name: "apples", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C001", name: "grapes", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C002", name: "apples", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C002", name: "grapes", type: "fruits", intime:[], quantity:[]}
             ]
</code>```

And below array as input,

```<code>record = [
    {code: "C001",
    records :[{intime: "15:32:12", apples: "30", grapes: "80"},
            {intime: "15:32:13", apples: "34", grapes: "50"}]
    },
    {code: "C002",
    records :[{intime: "15:32:12", apples: "56", grapes: "100"},
            {intime: "15:32:13", apples: "75", grapes: "38"}]
    },
]
</code>```

I want to put these values to arrays of report array as per matching condition so that report array should look like,

```<code>report = [
  {id: "id01", code: "C001", name: "apples", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[30,34]},
  {id: "id01", code: "C001", name: "grapes", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[80,50]},
  {id: "id01", code: "C002", name: "apples", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[56,75]},
  {id: "id01", code: "C002", name: "grapes", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[100,38]}
]
</code>```

I think , this can be achieved through array filter method in loop but that method does not seems efficient when record array is big in size.  Please suggest me some better and efficient way to put values in such way.

答:
```<code>const finalReport = report.map(rep => {
  let obj = { ...rep };

  const recordFoundByCode = record.find(rec => rec.code === obj.code);

  if (recordFoundByCode) {
    recordFoundByCode.records.forEach(item => {
      obj.intime.push(item.intime);
      obj.quantity.push(item[obj.name]);
    });
  }

  return obj;
});

console.log(finalReport) // <== your desired array
</code>```

Title: How to insert values to a nested array

Body:
I am having one report array of objects which is used to show report data on the dashboard as below,

    report = [
              {id: "id01", code: "C001", name: "apples", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C001", name: "grapes", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C002", name: "apples", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C002", name: "grapes", type: "fruits", intime:[], quantity:[]}
             ]

And below array as input,

record = [
    {code: "C001",
    records :[{intime: "15:32:12", apples: "30", grapes: "80"},
            {intime: "15:32:13", apples: "34", grapes: "50"}]
    },
    {code: "C002",
    records :[{intime: "15:32:12", apples: "56", grapes: "100"},
            {intime: "15:32:13", apples: "75", grapes: "38"}]
    },
]

I want to put these values to arrays of report array as per matching condition so that report array should look like,

report = [
  {id: "id01", code: "C001", name: "apples", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[30,34]},
  {id: "id01", code: "C001", name: "grapes", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[80,50]},
  {id: "id01", code: "C002", name: "apples", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[56,75]},
  {id: "id01", code: "C002", name: "grapes", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[100,38]}
]

I think , this can be achieved through array filter method in loop but that method does not seems efficient when record array is big in size.  Please suggest me some better and efficient way to put values in such way.


问:
Unable to get Web API controller method's URL
Env: C# Core 3.1 WebApi Project.

In my controller I'm trying to get the current URL but am getting a null value.  I've tried a number of things using the Url class:

```<code>var x = Url.Link("https://localhost:44397/api/Account/Accounts/", new { a = 1, b = 2 });
var y = Url.RouteUrl("www.xyz.com", new { a = 3, b = 4 });
var url = Url.Link("GetAuthors", authorsResourceParameters);
var r = Url.RouteUrl("This route");
var yd = Url.Action("myAction", "myController", authorsResourceParameters, "https");
</code>```

The Url class is from Microsoft.AspNetCore.Mvc.Routing.EndpointRoutingUrlHelper.  Is this the correct namespace?

What am I missing?

答:
You can use the below code:

```<code>var request = HttpContext.Request;

var uri = string.Concat(request.Scheme,"://",
                        request.Host.ToUriComponent(),
                        request.PathBase.ToUriComponent(),
                        request.Path.ToUriComponent(),
                        request.QueryString.ToUriComponent());
</code>```

good luck.

Body:
Env: C# Core 3.1 WebApi Project.

In my controller I'm trying to get the current URL but am getting a null value.  I've tried a number of things using the Url class:

var x = Url.Link("https://localhost:44397/api/Account/Accounts/", new { a = 1, b = 2 });
var y = Url.RouteUrl("www.xyz.com", new { a = 3, b = 4 });
var url = Url.Link("GetAuthors", authorsResourceParameters);
var r = Url.RouteUrl("This route");
var yd = Url.Action("myAction", "myController", authorsResourceParameters, "https");

The Url class is from Microsoft.AspNetCore.Mvc.Routing.EndpointRoutingUrlHelper.  Is this the correct namespace?

What am I missing?

Body:
You can use the below code:

var request = HttpContext.Request;

var uri = string.Concat(request.Scheme,"://",
                        request.Host.ToUriComponent(),
                        request.PathBase.ToUriComponent(),
                        request.Path.ToUriComponent(),
                        request.QueryString.ToUriComponent());

good luck.


问:
React keys - rendering 2 duplicate items in a list- how to avoid same key warning as same items are intended without using index as key?
I have a gallery of items. 2 items will always be the same for a memory card game (remembering 2 matching images). Now if I map through I get the error that each child should have unique key since I give id as the key. 2 of the items I render, however, are exactly the same. The only way I see is to give the index as a key, which is not good.

How can I accomplish this without passing in index.

```<code>state = {
 cards: [
   {id: 132, src="example.com/hello"},
   {id: 142, src="example.com/bye"},
   {id: 132, src="example.com/hello"},
   {id: 142, src="example.com/bye"}
 ]
}
this.state.cards.map((card)=> {
  return <div key={card.id}><img src={card.src} /> <div/>
}
</code>```

答:
@sushant has essentially answered but here's the code</p>

```<code>this.state.cards.map((card,index)=> {
  return <div key={index}><img src={card.src} /> <div/>
}
</code>```

Body:
I have a gallery of items. 2 items will always be the same for a memory card game (remembering 2 matching images). Now if I map through I get the error that each child should have unique key since I give id as the key. 2 of the items I render, however, are exactly the same. The only way I see is to give the index as a key, which is not good.

How can I accomplish this without passing in index.

state = {
 cards: [
   {id: 132, src="example.com/hello"},
   {id: 142, src="example.com/bye"},
   {id: 132, src="example.com/hello"},
   {id: 142, src="example.com/bye"}
 ]
}
this.state.cards.map((card)=> {
  return

}

Body:
@sushant has essentially answered but here's the code

this.state.cards.map((card,index)=> {
  return <div key={index}><img src={card.src} /> <div/>
}


问:
SVG file can't convert to an expected image in Itext7
I have an SVG file, when I used SvgConverter.convertToImage to convert it as an image and added into a PDF document, the output image isn't as expected. The image stroke size became much bigger than that of the SVG file. My svg plugin version is 7.1.9. How to fix such issue?
What's the expected chart:
The actual output in pdf is:

SvgConverterProperties props = new SvgConverterProperties();
FontProvider provider = new FontProvider();
provider.addFont(FontProgramFactory.createFont("fontname"));
props.setFontProvider(provider);
Image pdfImage = SvgConverter.convertToImage(new FileInputStream(imagePath), pdfDoc, props);
```

<p>The svg contents:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg version="1.1" id="Layer_1" xmlns:x="&ns_extend;" xmlns:i="&ns_ai;" xmlns:graph="&ns_graphs;"
  xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="17px" height="21px"
  viewBox="0 0 17 21" enable-background="new 0 0 17 21" xml:space="preserve">
<g>
   <g>
    <defs>
     <path id="SVGID_3_" d="M12.435,6.162c0,0.496-0.371,0.903-0.867,0.946l0.036,0.396c0.699-0.065,1.225-0.64,1.225-1.343H12.435z
      "/>
    </defs>
    <use xlink:href="#SVGID_3_"  overflow="visible" fill="#2156A3"/>
    <clipPath id="SVGID_4_">
     <use xlink:href="#SVGID_3_"  overflow="visible"/>
    </clipPath>

     <rect x="9.591" y="4.183" clip-path="url(#SVGID_4_)" fill="#2156A3" stroke="#518428" stroke-width="0.25" stroke-miterlimit="10" width="5.218" height="5.297"/>
    <use xlink:href="#SVGID_3_"  overflow="visible" fill="none" stroke="#2156A3" stroke-width="0.25" stroke-miterlimit="10"/>
   </g>
   <g>
    <defs>
     <path id="SVGID_5_" d="M11.17,4.509c0-0.357,0.289-0.646,0.647-0.646c0.357,0,0.647,0.289,0.647,0.646
      c0,0.356-0.29,0.648-0.647,0.648C11.459,5.157,11.17,4.866,11.17,4.509 M10.774,4.509c0,0.575,0.466,1.043,1.043,1.043
      c0.576,0,1.043-0.468,1.043-1.043c0-0.577-0.467-1.043-1.043-1.043C11.24,3.467,10.774,3.933,10.774,4.509"/>
    </defs>
    <use xlink:href="#SVGID_5_"  overflow="visible" fill="#2156A3"/>
    <clipPath id="SVGID_6_">
     <use xlink:href="#SVGID_5_"  overflow="visible"/>
    </clipPath>
     <rect x="8.796" y="1.489" clip-path="url(#SVGID_6_)" fill="#2156A3" stroke="#2156A3" stroke-width="0.25" stroke-miterlimit="10" width="6.041" height="6.043"/>
    <use xlink:href="#SVGID_5_"  overflow="visible" fill="none" stroke="#2156A3" stroke-width="0.25" stroke-miterlimit="10"/>
   </g>
</g>
</svg></code>```

Body:
I have an SVG file, when I used SvgConverter.convertToImage to convert it as an image and added into a PDF document, the output image isn't as expected. The image stroke size became much bigger than that of the SVG file. My svg plugin version is 7.1.9. How to fix such issue?
What's the expected chart:
The actual output in pdf is:

SvgConverterProperties props = new SvgConverterProperties();
FontProvider provider = new FontProvider();
provider.addFont(FontProgramFactory.createFont("fontname"));
props.setFontProvider(provider);
Image pdfImage = SvgConverter.convertToImage(new FileInputStream(imagePath), pdfDoc, props);

The svg contents:

<svg version="1.1" id="Layer_1" xmlns:x="&ns_extend;" xmlns:i="&ns_ai;" xmlns:graph="&ns_graphs;"
  xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="17px" height="21px"
  viewBox="0 0 17 21" enable-background="new 0 0 17 21" xml:space="preserve">
<g>
   <g>
    <defs>
     <path id="SVGID_3_" d="M12.435,6.162c0,0.496-0.371,0.903-0.867,0.946l0.036,0.396c0.699-0.065,1.225-0.64,1.225-1.343H12.435z
      "/>
    </defs>
    <use xlink:href="#SVGID_3_"  overflow="visible" fill="#2156A3"/>
    <clipPath id="SVGID_4_">
     <use xlink:href="#SVGID_3_"  overflow="visible"/>
    </clipPath>

     <rect x="9.591" y="4.183" clip-path="url(#SVGID_4_)" fill="#2156A3" stroke="#518428" stroke-width="0.25" stroke-miterlimit="10" width="5.218" height="5.297"/>
    <use xlink:href="#SVGID_3_"  overflow="visible" fill="none" stroke="#2156A3" stroke-width="0.25" stroke-miterlimit="10"/>
   </g>
   <g>
    <defs>
     <path id="SVGID_5_" d="M11.17,4.509c0-0.357,0.289-0.646,0.647-0.646c0.357,0,0.647,0.289,0.647,0.646
      c0,0.356-0.29,0.648-0.647,0.648C11.459,5.157,11.17,4.866,11.17,4.509 M10.774,4.509c0,0.575,0.466,1.043,1.043,1.043
      c0.576,0,1.043-0.468,1.043-1.043c0-0.577-0.467-1.043-1.043-1.043C11.24,3.467,10.774,3.933,10.774,4.509"/>
    </defs>
    <use xlink:href="#SVGID_5_"  overflow="visible" fill="#2156A3"/>
    <clipPath id="SVGID_6_">
     <use xlink:href="#SVGID_5_"  overflow="visible"/>
    </clipPath>
     <rect x="8.796" y="1.489" clip-path="url(#SVGID_6_)" fill="#2156A3" stroke="#2156A3" stroke-width="0.25" stroke-miterlimit="10" width="6.041" height="6.043"/>
    <use xlink:href="#SVGID_5_"  overflow="visible" fill="none" stroke="#2156A3" stroke-width="0.25" stroke-miterlimit="10"/>
   </g>
</g>
</svg>

Body:
iText 7 in current version (7.1.10) processes stroke-width incorrectly if it's specified in <use> elements (instead of in <path> elements which are referenced from that <use>). As a workaround you can specify stroke-width directly on path elements like that:

<svg version="1.1" id="Layer_1"
  xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="17px" height="21px"
  viewBox="0 0 17 21" enable-background="new 0 0 17 21" xml:space="preserve">
<g>
   <g>
    <defs>
     <path stroke-width="0.25" id="SVGID_3_" d="M12.435,6.162c0,0.496-0.371,0.903-0.867,0.946l0.036,0.396c0.699-0.065,1.225-0.64,1.225-1.343H12.435z
      "/>
    </defs>
    <use xlink:href="#SVGID_3_"  overflow="visible" fill="#2156A3"/>
    <clipPath id="SVGID_4_">
     <use xlink:href="#SVGID_3_"  overflow="visible"/>
    </clipPath>

     <rect x="9.591" y="4.183" clip-path="url(#SVGID_4_)" fill="#2156A3" stroke="#518428" stroke-width="0.25" stroke-miterlimit="10" width="5.218" height="5.297"/>
    <use xlink:href="#SVGID_3_"  overflow="visible" fill="none" stroke="#2156A3"  stroke-miterlimit="10"/>
   </g>
   <g>
    <defs>
     <path stroke-width="0.25" id="SVGID_5_" d="M11.17,4.509c0-0.357,0.289-0.646,0.647-0.646c0.357,0,0.647,0.289,0.647,0.646
      c0,0.356-0.29,0.648-0.647,0.648C11.459,5.157,11.17,4.866,11.17,4.509 M10.774,4.509c0,0.575,0.466,1.043,1.043,1.043
      c0.576,0,1.043-0.468,1.043-1.043c0-0.577-0.467-1.043-1.043-1.043C11.24,3.467,10.774,3.933,10.774,4.509"/>
    </defs>
    <use xlink:href="#SVGID_5_"  overflow="visible" fill="#2156A3"/>
    <clipPath id="SVGID_6_">
     <use xlink:href="#SVGID_5_"  overflow="visible"/>
    </clipPath>
     <rect x="8.796" y="1.489" clip-path="url(#SVGID_6_)" fill="#2156A3" stroke="#2156A3" stroke-width="0.25" stroke-miterlimit="10" width="6.041" height="6.043"/>
    <use xlink:href="#SVGID_5_"  overflow="visible" fill="none" stroke="#2156A3"  stroke-miterlimit="10"/>
   </g>
</g>
</svg>


问:
Safari - iPhone simulator debugging (via "develop") not showing anymore
I am using iPhone simulator to run a UIWebview, and Safari browser (on my mac) in order to debug the js / html / css code (via "develop" menu -> iPhone Simulator -> choosing my webview).

Yestarday, the iPhone-simulator option disappeared from my "develop" menu: (as you can see, the "iphone-simulator" is missing here (it is opened in the background and working...)

Any idea?

Edit: I am using iOS 7 iPhone simulator + Safari 7

Edit 2: Just tried opening a website on iphone-simulator's Safari browser (in addition to the UIWebview). No luck here as well...

答:
I restarted my simulator from Hardware->Restart and after that simulator option came in Safari Develop Menu.

Hope it will save someone's time.


问:
Showing an image based on a number range in Javascript
I am trying to create a javascript program that prompts the user for a number. If a user puts in a number that is less then 21, an image of soda will show. If the number is 21 or greater, the image is beer. There is an image of a bar that is shown when the page loads. Negatives and non-numbers are not allowed in the code. I have worked on this code for over a couple of days and the code does run. The only problem I have with it is that it will say that any input is an invalid entry. I have looked around for any solutions and I'm not sure what to do. I am new to javascript and any help would be appreciated.

Below is the javascript I am using:

```<code>function start()
{
  let button1 = document.getElementById("button1");
  button1.onclick = toggleContent;
}

function toggleContent()
{
  let number = document.getElementById('number');
  let liquid = document.getElementById('Bar');

  if parseInt(number <= 20)
  {
      liquid.src = 'assets/Soda.png';
      liquid.alt = 'Spicy water';
  }
  else if (number >= 21)
  {
    liquid.src = 'assets/Beer.png';
    liquid.alt = 'Angry Juice';
  }
  else if (isNaN(number) || number < 0)
  {
    alert("Invalid Entry. Enter a Number.")
  }
}
window.onload = start;
</code>```

Here is the HTML code that goes with it:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>ID Check?</title>
    <script src="scripts/pt2script.js"></script>
  </head>
  <body>
    <img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
    <p>Enter a number into the text box.</p>
    <input type="text" id="number" value="Enter a number...">
    <button onclick="toggleContent()" id="button1">Submit</button>
  </body>
</html>

</code>```

答:
You need to get the value from input and convert it to a number by using an unary plus +.

function start() {
    let button1 = document.getElementById("button1");
    button1.onclick = toggleContent;
}

function toggleContent() {
    let number = +document.getElementById('number').value; // take value as a number
    let liquid = document.getElementById('Bar');

    if (isNaN(number) || number < 0) { // move exit condition to top and exit early
        alert("Invalid Entry. Enter a Number.")
        return;
    }

    if (number <= 20) { // condition without parseint
        liquid.src = 'assets/Soda.png';
        liquid.alt = 'Spicy water';
    } else { // no need for another check
        liquid.src = 'assets/Beer.png';
        liquid.alt = 'Angry Juice';
    }
}

window.onload = start;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" placeholder="Enter a number..."><!-- use placeholder -->
<button onclick="toggleContent()" id="button1">Submit</button></code>```

Body:
I am trying to create a javascript program that prompts the user for a number. If a user puts in a number that is less then 21, an image of soda will show. If the number is 21 or greater, the image is beer. There is an image of a bar that is shown when the page loads. Negatives and non-numbers are not allowed in the code. I have worked on this code for over a couple of days and the code does run. The only problem I have with it is that it will say that any input is an invalid entry. I have looked around for any solutions and I'm not sure what to do. I am new to javascript and any help would be appreciated.

Below is the javascript I am using:

function start()
{
  let button1 = document.getElementById("button1");
  button1.onclick = toggleContent;
}

function toggleContent()
{
  let number = document.getElementById('number');
  let liquid = document.getElementById('Bar');

  if parseInt(number <= 20)
  {
      liquid.src = 'assets/Soda.png';
      liquid.alt = 'Spicy water';
  }
  else if (number >= 21)
  {
    liquid.src = 'assets/Beer.png';
    liquid.alt = 'Angry Juice';
  }
  else if (isNaN(number) || number < 0)
  {
    alert("Invalid Entry. Enter a Number.")
  }
}
window.onload = start;

Here is the HTML code that goes with it:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>ID Check?</title>

Enter a number into the text box.

    <input type="text" id="number" value="Enter a number...">
    <button onclick="toggleContent()" id="button1">Submit</button>

Body:
You need to get the value from input and convert it to a number by using an unary plus +.

function start() {
    let button1 = document.getElementById("button1");
    button1.onclick = toggleContent;
}

function toggleContent() {
    let number = +document.getElementById('number').value; // take value as a number
    let liquid = document.getElementById('Bar');

    if (isNaN(number) || number < 0) { // move exit condition to top and exit early
        alert("Invalid Entry. Enter a Number.")
        return;
    }

    if (number <= 20) { // condition without parseint
        liquid.src = 'assets/Soda.png';
        liquid.alt = 'Spicy water';
    } else { // no need for another check
        liquid.src = 'assets/Beer.png';
        liquid.alt = 'Angry Juice';
    }
}

window.onload = start;

<img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
<p>Enter a number into the text box.</p>
<input type="text" id="number" placeholder="Enter a number..."><!-- use placeholder -->
<button onclick="toggleContent()" id="button1">Submit</button>


问:
Git equivalent of which/whence
When I run git help -a it shows me the list of internal commands, all of my aliases, and all of my external git commands (i.e. any executable starting with git- in my path). What I'd like is an alias or script that I can run as git which that will tell me one of the following:

command not found (e.g. git which notacommand)

built-in command (e.g. git which checkout)

the full path to the command (e.g. git which pwd would show /usr/local/bin/git-pwd)

the alias text (e.g. git which wtf would show alias.wtf blame -w)

I could write a script pretty easily to use the output of git help -a and produce this, but is there some git command I'm missing that already provides some or all of this functionality?

Update

Thanks to the comment and answer from @jthill I came up with the following git-which script:

#!/bin/sh

if test $# -ne 1
then
        echo "Usage: $0 <git command>" >&2
        exit 1
fi

CMD=git-"$1"

if PATH="$(git --exec-path)" command -v "$CMD" >/dev/null
then
    echo "$1: git built-in command"
    exit 0
elif command -v "$CMD"
then
    exit 0
elif git config --get-regexp '^alias\.'"$1"'$' |\
    sed 's/^alias\.\([^\s]\+\)/\1: aliased to /'
then
        exit 0
fi

echo "$1 not found"
exit 1
```

答:
git help will show you aliases, say git help wtf and it'll say 'wtf' is aliased to 'blame -w'. For the rest, hunting up libexec/git-core isn't hard, say git --exec-path, and which already hunts up commands, so

```<code>PATH=$(git --exec-path):$PATH which git-checkout
</code>```

will do your hunting for you, aliases can't override builtins so (fingers-to-textbox warning:)

```<code>f() { PATH=$(git --exec-path)${PATH+:$PATH} which git-$1 2>&- || git help $1; }
</code>```

looks like a decent start.

Title: Git equivalent of which/whence

Body:
git help will show you aliases, say git help wtf and it'll say 'wtf' is aliased to 'blame -w'. For the rest, hunting up libexec/git-core isn't hard, say git --exec-path, and which already hunts up commands, so

PATH=$(git --exec-path):$PATH which git-checkout

will do your hunting for you, aliases can't override builtins so (fingers-to-textbox warning:)

f() { PATH=$(git --exec-path)${PATH+:$PATH} which git-$1 2>&- || git help $1; }

looks like a decent start.


问:
SQLAlchemy(Python)/Sequelize(Node.js) rollback transation (undo button)
So I am right now developing a backend API using GraphQL and either Python with SQLAlchemy or Node.js with Sequelize to write all the data into a SQLite database.

I am still not sure what backend I will end up with. Maybe this question and the answer to my question will lead me to using one or the other.

So my app will have a function where you add dart throws (like double 20, triple 19, ...) into a table with throws. Depending on the game chosen and the conditions chosen this throw will either substract from a total count or maybe be added into a counter table or something like that.

Everytime a throw gets added there will be a check if the game is won and some other checks as well. Those might also write (commit) data to the database.

Now, if the user types in the wrong number / or the automatic darts machine will discover the wrong throw number (malfunction) there is a throw and several changed data in the database which I will have to rollback.

In darts scorer apps you will find in the app store either ios or android you always will have a undo button which will erase the throw from the database and all the "effects" caused by entering the wrong throw.

As a former mssql administrator my first idea was transactional logs and rollback function. But after searching the net for a while I understand both SQLAlchemy and Sequelize will rollback transactions only on exception.

Can I purposely rollback the last "complete" transaction (meaning all changes which for example a function will make by the end of the function) by hitting a button / calling a rest api path like '/undo' and if so are there any code snippets for either SQLAlchemy or Sequelize I am missing?

Best regards,
Patrick

edit:

collection of provided answers:

command pattern (python)

答:
According to Can I rollback a transaction I've already committed? (data loss) and other sources, no, you cannot rollback a committed transaction. Also this is DB dependent, so doesn't have to do much with ORM or language.

I would recommend to implement the Command pattern, which is great for Undo. So basically do the revert from code, not from the database.


问:
What is the String 'volumeName' argument of MediaStore.Audio.Playlists.Members.getContentUri referring to?
I am wanting to query the members of a given playlist.  I have the correct playlist id, and want to use a managedQuery() to look at the playlist members in question.

What I have is this:

```<code>private String [] columns = {
     MediaStore.Audio.Playlists.Members.PLAYLIST_ID,
     MediaStore.Audio.Playlists.Members.TITLE,
     };
Uri membersUri = MediaStore.Audio.Playlists.Members.getContentUri(volume, playlistId);
Cursor tCursor = managedQuery(membersUri, columns, null, null, null);
</code>```

I don't know what the volume argument needs to be.  I've tried this:
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI.toString() for the "volume" argument.

That gives me back a valid content URI that looks like:

```<code>content://media/external/audio/playlists/2/members
</code>```

However, my cursor comes back null.  I probably am way off base -- I know what I want to do is very simple.

答:
Judging by the code in android.provider.MediaStore, it can be either "internal" or "external"

/**
 * The content:// style URI for the internal storage.
 */
public static final Uri INTERNAL_CONTENT_URI =
        getContentUri("internal");

/**
 * The content:// style URI for the "primary" external storage
 * volume.
 */
public static final Uri EXTERNAL_CONTENT_URI =
        getContentUri("external");```

ContentLicense: CC BY-SA 2.5

Body:
I am wanting to query the members of a given playlist.  I have the correct playlist id, and want to use a managedQuery() to look at the playlist members in question.

What I have is this:

private String [] columns = {
     MediaStore.Audio.Playlists.Members.PLAYLIST_ID,
     MediaStore.Audio.Playlists.Members.TITLE,
     };
Uri membersUri = MediaStore.Audio.Playlists.Members.getContentUri(volume, playlistId);
Cursor tCursor = managedQuery(membersUri, columns, null, null, null);

I don't know what the volume argument needs to be.  I've tried this:
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI.toString() for the "volume" argument.

That gives me back a valid content URI that looks like:

content://media/external/audio/playlists/2/members

However, my cursor comes back null.  I probably am way off base -- I know what I want to do is very simple.


问:
Resize background image in div using css
Below css sets an individual background on two divs; the images repeat themselves if they do not fit into the div size.

How can I stretch the images using css to fit into space required by div ?

```<code><style type="text/css">
#contentMain {
  margin-bottom: 5%;
  margin-top: 10%;
  margin-left: 10%;
  margin-right: 10%;
  background: url( /jQuery/mypage/img/background1.png )
}
#page1 {
  background: url( /jQuery/mypage/img/background2.png )
}
</style>
</code>```

答:
Answer

You have multiple options:

background-size: 100% 100%; - image gets stretched (aspect ratio may be preserved, depending on browser)

background-size: contain; - image is stretched without cutting it while  preserving aspect ratio

background-size: cover; - image is completely covering the element while  preserving aspect ratio (image can be cut off)

/edit: And now, there is even more: https://alligator.io/css/cropping-images-object-fit

Demo on Codepen

Update 2017: Preview

Here are screenshots for some browsers to show their differences.

Chrome

Firefox

Edge

IE11

Takeaway Message

background-size: 100% 100%; produces the least predictable result.

Resources

https://alligator.io/css/cropping-images-object-fit


问:
Wait for Observable to Complete Inside of Array.Map
I have an array of objects in which one of the keys includes a customer id.

```<code>const customerArray = [{ customerId: 123, ...}, { customerId: 456, ...}];
</code>```

I want to iterate through this array and make an api call to get further details about this customer from a separate endpoint.

```<code>const mapped = customerArray
  .map(customer => ({
    customerId: customer.customerId,
    rating: this.productService(customer.customerId)
               .pipe(map(rating => rating))}));
</code>```

My expectation is that I would then have an array that includes an object with the following shape:

```<code>{
  customerId: number,
  rating: number
}
</code>```

Instead, I end up with:

```<code>{
  customerId: number,
  rating: Observable
}
</code>```

My productService call returns on observable and is used elsewhere in the app successfully. I need to have my map wait for the call to complete on the rating key before mapping to the next item in the array.

答:
I got a stackblitz setup that shows a way you can manage it, but for the sake of keeping it always available

import { Observable, of, from } from 'rxjs';
import { map, mergeMap, combineAll } from 'rxjs/operators';

const custArray = [{customerId: 1}, {customerId: 2}, {customerId: 3}];

function mapSomeStuff(id: number): Observable<number> {
  return of(id * id);
}

function doProductStuff(custArr: Array<{customerId: number}>): Observable<Array<{ customerId: number, rating: number}>> {
  return from(custArray)
    .pipe(
      map(async (cust) => ({
        customerId: cust.customerId,
        rating: await mapSomeStuff(cust.customerId).toPromise()
    })),
    combineAll()
  );
}

doProductStuff(custArray).subscribe(x => console.log(x))
```

This breaks up the array and creates an observable for each value in the array, runs the service, converts the observable to a promise and gets the final value of it, then combines all of the observables into a single observable with an array of values being the final out. You can check the output and see [Object, Object, Object] and check to see that the customerId and rating are available on each Object.

Body:
I have an array of objects in which one of the keys includes a customer id.

const customerArray = [{ customerId: 123, ...}, { customerId: 456, ...}];

I want to iterate through this array and make an api call to get further details about this customer from a separate endpoint.

const mapped = customerArray
  .map(customer => ({
    customerId: customer.customerId,
    rating: this.productService(customer.customerId)
               .pipe(map(rating => rating))}));

My expectation is that I would then have an array that includes an object with the following shape:

{
  customerId: number,
  rating: number
}

Instead, I end up with:

{
  customerId: number,
  rating: Observable
}

My productService call returns on observable and is used elsewhere in the app successfully. I need to have my map wait for the call to complete on the rating key before mapping to the next item in the array.

Body:
I got a stackblitz setup that shows a way you can manage it, but for the sake of keeping it always available

import { Observable, of, from } from 'rxjs';
import { map, mergeMap, combineAll } from 'rxjs/operators';

const custArray = [{customerId: 1}, {customerId: 2}, {customerId: 3}];

function mapSomeStuff(id: number): Observable<number> {
  return of(id * id);
}

function doProductStuff(custArr: Array<{customerId: number}>): Observable<Array<{ customerId: number, rating: number}>> {
  return from(custArray)
    .pipe(
      map(async (cust) => ({
        customerId: cust.customerId,
        rating: await mapSomeStuff(cust.customerId).toPromise()
    })),
    combineAll()
  );
}

doProductStuff(custArray).subscribe(x => console.log(x))

This breaks up the array and creates an observable for each value in the array, runs the service, converts the observable to a promise and gets the final value of it, then combines all of the observables into a single observable with an array of values being the final out. You can check the output and see [Object, Object, Object] and check to see that the customerId and rating are available on each Object.