问:
Angular JWT with few Roles acess
I want to use several roles for accessing views in the application, if I use one role everything works correctly, however when I use several roles, the views do not give access

My model User have this:

```<code>export class User {
    role: Role[];                // I change - role: Role[] for few roles
    expiresIn: string;
    aud: string;
    iss: string;
    token?: string;
}

export const enum Role {
    Admin = 'admin',
    User = 'user',
    Engineer = 'engineer'
}
</code>```

my backend give my token with with roles:

```<code>//....
role: (2) ["admin", "engineer"]
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ
//....
</code>```

If I use this in login metod

```<code>tokenInfo['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'][0]   - first element in array
</code>```

i have only 1 role, and code work fine, but I can have many users who belong to different roles, and I need the application to give them access if there are at least 1 role

I handle token decoding and getting roles in authorization service

```<code>signin(username:string, password:string ) {
    return this.http.post<User>(`${environment.apiUrl}${environment.apiVersion}Profile/Login`, {username, password})
    .pipe(map(user => {
    if (user && user.token) {
      let tokenInfo = this.getDecodedAccessToken(user.token); // decode token
      this.session = {
        token: user.token,
        role: tokenInfo['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'],     - add this [0]
        expiresIn: tokenInfo.exp,
        aud: tokenInfo.aud,
        iss: tokenInfo.iss,
      }
      localStorage.setItem('currentUser', JSON.stringify(this.session));
      this.currentUserSubject.next(this.session);
    }
    return this.session;
    }))
}
</code>```

sigin metod for example

```<code>Login() {
    this.auth.signin(this.signinForm.value.email, this.signinForm.value.password)
        .pipe(first())
        .subscribe(
            data => {
                console.log("User is logged in");
                this.router.navigate(['/dashboard']);
                this.loading = false;
            });
  }
</code>```

Not sure if I correctly specify multiple access roles

```<code>//......
const adminRoutes: Routes = [
{
    path: 'dashboard',
    loadChildren: () => import('./views/dashboard/dashboard.module').then(m => m.DashboardModule),
    canActivate: [AuthGaurd],

},
{
    path: 'books',
    loadChildren: () => import('./views/books/books.module').then(m => m.BooksModule),
    canActivate: [AuthGaurd],
    data: { roles: [Role.Admin] }  <- work fine if 1 role
},
{
    path: 'person',
    loadChildren: () => import('./views/person/person.module').then(m => m.PersonModule),
    canActivate: [AuthGaurd],
    data: { roles: [Role.Admin, Role.Engineer] }  <- if have 1 role - admin - open
 },
 {
    path: 'eqip',
    loadChildren: () => import('./views/eqip/eqip.module').then(m => m.PersonModule),
    canActivate: [AuthGaurd],
    data: { roles: [Role.Engineer] }  <- not open becouse only admin role
 }];

const routes: Routes = [
{
    path: '',
    redirectTo: 'applayout-sidebar-compact/dashboard/v1',
    pathMatch: 'full',
},
...
{
    path: '**',
    redirectTo: 'others/404'
}];

@NgModule({
imports: [RouterModule.forRoot(routes, { useHash: true })],
exports: [RouterModule]
})
export class AppRoutingModule { }
//......
</code>```

and guard sevice

```<code>  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const url: string = state.url;
const currentUser = this.auth.currentUserValue;
// in auth.service.ts
// constructor(private http: HttpClient) {
//   this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
//   this.currentUser = this.currentUserSubject.asObservable();

// }
// public get currentUserValue(): User {
//   return this.currentUserSubject.value;
// }
if (this.auth.isUserLoggedIn()) {

  // test code
  const ter = route.data.roles.includes(currentUser.role) <- Error now here
  console.log(ter)

  // main check role code
  // if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
  //   this.router.navigate(["/"]);
  //   return false;
  // }

  return true;

}
this.auth.setRedirectUrl(url);
this.router.navigate([this.auth.getLoginUrl()]);
return false;
</code>```

}

token in localStorage:

```<code>aud: "Service"
expiresIn: 1591967261
iss: "USs"
role: ["admin", "engineer"]
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHR....
</code>```

change app-routing.module.ts

```<code>@NgModule({
imports: [RouterModule.forRoot(routes, {
    useHash: true,
    initialNavigation: 'enabled',
    paramsInheritanceStrategy: 'always',
    relativeLinkResolution: 'corrected',
    scrollPositionRestoration: 'enabled',
})],
exports: [RouterModule]
</code>```

Error

```<code>Uncaught (in promise): TypeError: Cannot read property 'includes' of undefined
</code>```

TypeError: Cannot read property 'includes' of undefined

答:
It could also be that a typescript enum is not a string.
so comparing a enum with a string will never be true.

What you need to use is a const enum because that compiles down to a string.

try changing to

export const enum Role {
    Admin = 'admin',
    User = 'user',
    Engineer = 'engineer'
}
```

<p>Though this does have other implications.
https://www.typescriptlang.org/docs/handbook/enums.html#const-enums</p>

<p>and instead of doing a indexOf you can use <code>.includes</code></p>

<pre class="lang-js prettyprint-override"><code>route.data.roles.includes(currentUser.role)
</code>```

Edit:
It could also be that your data is not inherited down to where you are trying to get it.

You might need to add this to your Router config

```<code>RouterModule.forRoot([], {
      initialNavigation: 'enabled',
      paramsInheritanceStrategy: 'always', <-- this makes params and data accessible lower down into the tree
      relativeLinkResolution: 'corrected',
      scrollPositionRestoration: 'enabled',
    }),
</code>```

```<code>
</code>```

Title: Angular JWT with few Roles acess

Body:
I want to use several roles for accessing views in the application, if I use one role everything works correctly, however when I use several roles, the views do not give access

My model User have this:

export class User {
    role: Role[];                // I change - role: Role[] for few roles
    expiresIn: string;
    aud: string;
    iss: string;
    token?: string;
}

export const enum Role {
    Admin = 'admin',
    User = 'user',
    Engineer = 'engineer'
}

my backend give my token with with roles:

//....
role: (2) ["admin", "engineer"]
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ
//....

If I use this in login metod

tokenInfo['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'][0]   - first element in array

i have only 1 role, and code work fine, but I can have many users who belong to different roles, and I need the application to give them access if there are at least 1 role

I handle token decoding and getting roles in authorization service

signin(username:string, password:string ) {
    return this.http.post<User>(`${environment.apiUrl}${environment.apiVersion}Profile/Login`, {username, password})
    .pipe(map(user => {
    if (user && user.token) {
      let tokenInfo = this.getDecodedAccessToken(user.token); // decode token
      this.session = {
        token: user.token,
        role: tokenInfo['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'],     - add this [0]
        expiresIn: tokenInfo.exp,
        aud: tokenInfo.aud,
        iss: tokenInfo.iss,
      }
      localStorage.setItem('currentUser', JSON.stringify(this.session));
      this.currentUserSubject.next(this.session);
    }
    return this.session;
    }))
}

sigin metod for example

Login() {
    this.auth.signin(this.signinForm.value.email, this.signinForm.value.password)
        .pipe(first())
        .subscribe(
            data => {
                console.log("User is logged in");
                this.router.navigate(['/dashboard']);
                this.loading = false;
            });
  }

Not sure if I correctly specify multiple access roles

//......
const adminRoutes: Routes = [
{
    path: 'dashboard',
    loadChildren: () => import('./views/dashboard/dashboard.module').then(m => m.DashboardModule),
    canActivate: [AuthGaurd],

},
{
    path: 'books',
    loadChildren: () => import('./views/books/books.module').then(m => m.BooksModule),
    canActivate: [AuthGaurd],
    data: { roles: [Role.Admin] }  <- work fine if 1 role
},
{
    path: 'person',
    loadChildren: () => import('./views/person/person.module').then(m => m.PersonModule),
    canActivate: [AuthGaurd],
    data: { roles: [Role.Admin, Role.Engineer] }  <- if have 1 role - admin - open
 },
 {
    path: 'eqip',
    loadChildren: () => import('./views/eqip/eqip.module').then(m => m.PersonModule),
    canActivate: [AuthGaurd],
    data: { roles: [Role.Engineer] }  <- not open becouse only admin role
 }];

const routes: Routes = [
{
    path: '',
    redirectTo: 'applayout-sidebar-compact/dashboard/v1',
    pathMatch: 'full',
},
...
{
    path: '**',
    redirectTo: 'others/404'
}];

@NgModule({
imports: [RouterModule.forRoot(routes, { useHash: true })],
exports: [RouterModule]
})
export class AppRoutingModule { }
//......

and guard sevice

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const url: string = state.url;
const currentUser = this.auth.currentUserValue;
// in auth.service.ts
// constructor(private http: HttpClient) {
//   this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
//   this.currentUser = this.currentUserSubject.asObservable();

// }
// public get currentUserValue(): User {
//   return this.currentUserSubject.value;
// }
if (this.auth.isUserLoggedIn()) {

  // test code
  const ter = route.data.roles.includes(currentUser.role) <- Error now here
  console.log(ter)

  // main check role code
  // if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
  //   this.router.navigate(["/"]);
  //   return false;
  // }

  return true;

}
this.auth.setRedirectUrl(url);
this.router.navigate([this.auth.getLoginUrl()]);
return false;

}

token in localStorage:

aud: "Service"
expiresIn: 1591967261
iss: "USs"
role: ["admin", "engineer"]
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHR....

change app-routing.module.ts

@NgModule({
imports: [RouterModule.forRoot(routes, {
    useHash: true,
    initialNavigation: 'enabled',
    paramsInheritanceStrategy: 'always',
    relativeLinkResolution: 'corrected',
    scrollPositionRestoration: 'enabled',
})],
exports: [RouterModule]

Error

Uncaught (in promise): TypeError: Cannot read property 'includes' of undefined

TypeError: Cannot read property 'includes' of undefined

Body:
It could also be that a typescript enum is not a string.
so comparing a enum with a string will never be true.

What you need to use is a const enum because that compiles down to a string.

try changing to

export const enum Role {
    Admin = 'admin',
    User = 'user',
    Engineer = 'engineer'
}

Though this does have other implications.
https://www.typescriptlang.org/docs/handbook/enums.html#const-enums

and instead of doing a indexOf you can use .includes

route.data.roles.includes(currentUser.role)

Edit:
It could also be that your data is not inherited down to where you are trying to get it.

You might need to add this to your Router config

RouterModule.forRoot([], {
      initialNavigation: 'enabled',
      paramsInheritanceStrategy: 'always', <-- this makes params and data accessible lower down into the tree
      relativeLinkResolution: 'corrected',
      scrollPositionRestoration: 'enabled',
    }),


来源: stackexchange

问:
BroadcastReceiver on new app installs
I want to receive a notification when a new application is installed.

```<code>IntentFilter newAppFilter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
newAppFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
newAppFilter.addAction(Intent.ACTION_PACKAGE_INSTALL);
newAppFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
getApplicationContext().registerReceiver(newAppReceiver, newAppFilter);

public static BroadcastReceiver newAppReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
            Log.e("Broadcast","Received");
       }
};
</code>```

But I am not able to get any log. Anyone can help me?

答:
Try to add data scheme to your IntentFilter.

```<code>newAppFilter.addDataScheme("package");
</code>```

Reference: IntentFilter.addDataScheme() documentation

If no schemes are included, then an
  Intent will match only if it includes
  no data.

ContentLicense: CC BY-SA 3.0

Title: BroadcastReceiver on new app installs

Body:
I want to receive a notification when a new application is installed.

IntentFilter newAppFilter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
newAppFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
newAppFilter.addAction(Intent.ACTION_PACKAGE_INSTALL);
newAppFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
getApplicationContext().registerReceiver(newAppReceiver, newAppFilter);

public static BroadcastReceiver newAppReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
            Log.e("Broadcast","Received");
       }
};

But I am not able to get any log. Anyone can help me?

Body:
Try to add data scheme to your IntentFilter.

newAppFilter.addDataScheme("package");

Reference: IntentFilter.addDataScheme() documentation

If no schemes are included, then an
  Intent will match only if it includes
  no data.

ContentLicense: CC BY-SA 4.0


问:
Regular Expression for a Kibana Search
I am trying to create a regular expression search within Kibana. I am new to regex and new to kibana, but the solution to this issue should not be too complex.

Right now I am filtering through the "message" field of a query of searches for the specific text Max Memory Used. Currently the search is returning all messages with that text field. However, the "Max Memory Used" phrase is followed by a statistic for example Max Memory Used: 65 MB. The issue I am having is that I do not know how to create the regex search to return both the Max Memory Used, and the __ MB, as the number of MB used is different every time.

The current used filter reads "Max Memory Used" in the search field.

答:
Try the regex below:

```<code>/^\bMax\b \bMemory\b \bUsed\b: \d+? [MmKkGgTt]?[Bb]$/
</code>```

Explanation of the above regex:

^ - Represents the start of the given test String.

\b - Represents the word boundary.

\d+? - Represents the digit class matching one or more digits lazily.

[MmKkGgTt]? - Represents a character matching the characters among the given class zero or one time. Since the size can be in KB, GB, MB or even just B. You can add them accordingly.

$ - Represents end of the given test String.

You can find the demo of the above regex here.

Title: Regular Expression for a Kibana Search

Body:
Try the regex below:

/^\bMax\b \bMemory\b \bUsed\b: \d+? [MmKkGgTt]?[Bb]$/

Explanation of the above regex:

^ - Represents the start of the given test String.

\b - Represents the word boundary.

\d+? - Represents the digit class matching one or more digits lazily.

[MmKkGgTt]? - Represents a character matching the characters among the given class zero or one time. Since the size can be in KB, GB, MB or even just B. You can add them accordingly.

$ - Represents end of the given test String.

You can find the demo of the above regex here.


问:
Knapsack problem where there are three arrays: weight of an item array, value of an item array and amount of an item array
What would be the solution to this problem? I think it would be rather tricky because you would have to juggle three characteristics.

Here is my attempt:
p-value, s-weight, k-amount, max-maximum weight,

m-number of items to take

static int solution(int[] s, int[] p, int[] k, int max)
        {

```<code>        int[,] matrix = new int[s.Length + 1, max + 1];

        for (int i = 1; i <= s.Length; i++)
        {

            for (int j = 0; j <= max; j++)
            {

                int m = 1;
                for(int z = k[i - 1]; z > 0; z--)
                {
                    if(z * s[i - 1] <= j)
                    {
                        m = z;
                        break;

                    }
                }

                if (s[i - 1] * m <= j)
                {
                    matrix[i, j] =
                        Math.Max((p[i - 1] * m) + matrix[i - 1, j - s[i - 1] * m],
                    matrix[i - 1, j]);
                }
                else
                {
                    matrix[i, j] = matrix[i - 1, j];
                }

            }
        }

        return matrix[s.Length, max];
    }
</code>```

答:
For knapsack with some amount of item copies there's a nice trick to reduce it to classical knapsack:

Let's say we have x copies of some item weighting w and giving value v

Notice that it's the same as having log x items where each item has w, 2*w, 4*w, ... weight and v, 2*v, 4*vvalue and sum of all weights is same as w*x

In cases where x can't be expressed as sum of powers of 2 we can make last number what's left (i.e. if x=10, our weight distribution is: 1 + 2 + 4 + 3 = 10). The important thing is to choose such weights that all possible pickings of 1..x are possible to make by picking some subset

After this the problem is reduced to classical knapsack.

Complexity O(#items * #maxWeight * log2(#MaxItemCount)

Body:
What would be the solution to this problem? I think it would be rather tricky because you would have to juggle three characteristics.

Here is my attempt:
p-value, s-weight, k-amount, max-maximum weight,

m-number of items to take

static int solution(int[] s, int[] p, int[] k, int max)
        {

        int[,] matrix = new int[s.Length + 1, max + 1];

        for (int i = 1; i <= s.Length; i++)
        {

            for (int j = 0; j <= max; j++)
            {

                int m = 1;
                for(int z = k[i - 1]; z > 0; z--)
                {
                    if(z * s[i - 1] <= j)
                    {
                        m = z;
                        break;

                    }
                }

                if (s[i - 1] * m <= j)
                {
                    matrix[i, j] =
                        Math.Max((p[i - 1] * m) + matrix[i - 1, j - s[i - 1] * m],
                    matrix[i - 1, j]);
                }
                else
                {
                    matrix[i, j] = matrix[i - 1, j];
                }

            }
        }

        return matrix[s.Length, max];
    }


问:
Spring boot in app engine connection with cloud sql
Trying to connect spring boot application deployed at app engine standard environment with cloud MySql throws following error.

GCLOUD: java.sql.SQLNonTransientConnectionException: Cannot connect to MySQL server on localhost:3,306.
GCLOUD: Make sure that there is a MySQL server running on the machine/port you are trying to connect to and that the machine this software is running on is able to connect to this host/port (i.e. not firewalled). Also make sure that the server has not been started with the --skip-networking flag.

```<code>config.setDriverClassName("com.mysql.cj.jdbc.Driver");
config.setJdbcUrl(String.format("jdbc:mysql:///%s", DB_NAME));
config.setUsername(USER_NAME);
config.setPassword(USER_PW);
config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.mysql.socket.factory.connector.j.8");
String CLOUD_SQL_CONNECTION_NAME = "PROJECTID:REGION:DB_INSTANCE";
config.addDataSourceProperty("cloudSqlInstance", CLOUD_SQL_CONNECTION_NAME);
</code>```

'IAM' roles and other setting made in app engine as suggested here.
Am I missing something?

答:
I ran into the same thing, and (several headaches later) came across a solution that works for me. It came down to the dependencies stated in pom.xml (for maven).

I was using:

```<code><dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>1.22.0</version>
</dependency>
</code>```

which I think I got from some other tutorial.

Instead, replacing it with the following fixed the issue:

```<code><dependency>
    <groupId>com.google.cloud.sql</groupId>
    <artifactId>mysql-socket-factory</artifactId>
    <version>1.0.16</version>
</dependency>
</code>```

This I found through a tutorial video (in itself quite helpful): https://www.youtube.com/watch?v=mAhah-vq0Iw

Body:
Trying to connect spring boot application deployed at app engine standard environment with cloud MySql throws following error.

GCLOUD: java.sql.SQLNonTransientConnectionException: Cannot connect to MySQL server on localhost:3,306.
GCLOUD: Make sure that there is a MySQL server running on the machine/port you are trying to connect to and that the machine this software is running on is able to connect to this host/port (i.e. not firewalled). Also make sure that the server has not been started with the --skip-networking flag.

config.setDriverClassName("com.mysql.cj.jdbc.Driver");
config.setJdbcUrl(String.format("jdbc:mysql:///%s", DB_NAME));
config.setUsername(USER_NAME);
config.setPassword(USER_PW);
config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.mysql.socket.factory.connector.j.8");
String CLOUD_SQL_CONNECTION_NAME = "PROJECTID:REGION:DB_INSTANCE";
config.addDataSourceProperty("cloudSqlInstance", CLOUD_SQL_CONNECTION_NAME);

'IAM' roles and other setting made in app engine as suggested here.
Am I missing something?

Body:
I ran into the same thing, and (several headaches later) came across a solution that works for me. It came down to the dependencies stated in pom.xml (for maven).

I was using:

<dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>1.22.0</version>
</dependency>

which I think I got from some other tutorial.

Instead, replacing it with the following fixed the issue:

<dependency>
    <groupId>com.google.cloud.sql</groupId>
    <artifactId>mysql-socket-factory</artifactId>
    <version>1.0.16</version>
</dependency>

This I found through a tutorial video (in itself quite helpful): https://www.youtube.com/watch?v=mAhah-vq0Iw


问:
Sanic CORS Exception handler
I have tried to use Sanic_CORS in exception handler like error 404,
but I received CORS error
Access to XMLHttpRequest at 'http://backend:port/endpoint' from origin 'http://react_app:port' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
There are no problems with valid endpoints.

My error handler

```<code>@app.exception(NotFound)
async def ignore_404s(request, exception):
    return response.json({'message': "Oops, server error"},
                          status=404)
</code>```

How can I implement Sanic_CORS for error handlers? Any ideas?

答:
One option would be to just add the header into your response. Albeit, this is not using the sanic-cors package, but you really do not need it here.

@app.exception(NotFound)
async def ignore_404s(request, exception):
    return response.json(
        {'message': "Oops, server error"},
        status=404,
        headers={"Access-Control-Allow-Origin": "*"}
    )
```

Title: Sanic CORS Exception handler

Body:
I have tried to use Sanic_CORS in exception handler like error 404,
but I received CORS error
Access to XMLHttpRequest at 'http://backend:port/endpoint' from origin 'http://react_app:port' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
There are no problems with valid endpoints.

My error handler

@app.exception(NotFound)
async def ignore_404s(request, exception):
    return response.json({'message': "Oops, server error"},
                          status=404)

How can I implement Sanic_CORS for error handlers? Any ideas?


问:
Mule exception strategy
On one particular queue alone the Mule JMS consumer count goes to 0 and comes back to default numbers after a point in time

My question is, why is it going down to 0 and I have message stuck in the queue? After few moments I find it comes back to 32 (default numberOfConcurrentTransactedRecievers) and processes the message and then again goes back to 0 consumers. What could be the problem?

I've other consumers in the same mule which are able to process cleanly without the count reducing.

My Configs:

<spring:bean id="domainConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory" lazy-init="true">
    <spring:property name="brokerURL" value="tcp://78.99.88.72:61616?jms.prefetchPolicy.all=2&jms.useAsyncSend=true&socketBufferSize=131072" />
    <spring:property name="redeliveryPolicy" ref="domainRedeliveryPolicy" />
</spring:bean>

<spring:bean id="amqExceptionConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory" lazy-init="true">
    <spring:property name="brokerURL" value="failover:(${domain.amq.failover.url}?jms.prefetchPolicy.all=2)" />
    <spring:property name="redeliveryPolicy" ref="domainRedeliveryPolicy" />
</spring:bean>
```

<pre class="lang-xml prettyprint-override"><code><jms:activemq-connector
    name="com.KKT.jmsConnector"
    username="${domain.amq.user.id}"
    password="${domain.amq.user.password}"
    connectionFactory-ref="pooledConnectionFactory"
    validateConnections="true"
    numberOfConcurrentTransactedReceivers="32"
    acknowledgementMode="AUTO_ACKNOWLEDGE"
    persistentDelivery="false"
    doc:name="AMQ Connector for KKTInterface"
    specification="1.1">
    <receiver-threading-profile maxThreadsActive="32" poolExhaustedAction="WAIT"/>
    <dispatcher-threading-profile maxThreadsActive="128" poolExhaustedAction="WAIT"/>
    <reconnect count="15" frequency="5000" blocking="true"/>
</jms:activemq-connector>
</code>```

And I see the below error:

```<code>mule.log.5:2020-05-29 20:24:49,392 [ERROR] KKT.router [ActiveMQ Session Task-6] | ed938f60-a1d8-11ea-8ad7-525400aef612: KKT Interface: Unrecoverable Error: Please check ASAP: org.mule.transport.jms.redelivery.MessageRedeliveredException: "Message with id "ID:localhost-35511-1590775568949-1:1:162:1:3367" has been redelivered 1 times on endpoint "jms://com.KKT.router.inbox", which exceeds the maxRedelivery setting of 0 on the connector "com.KKT.router.jmsConnector".
mule.log.5:2020-05-29 20:24:49,216 [ERROR] exception.CatchMessagingExceptionStrategy [ActiveMQ Session Task-5] |
mule.log.5:2020-05-29 20:24:49,216 [ERROR] exception.CatchMessagingExceptionStrategy [ActiveMQ Session Task-4] |
mule.log.9:2020-05-29 20:24:32,753 [ERROR] exception.CatchMessagingExceptionStrategy [ActiveMQ Session Task-57] |
mule.log.9:2020-05-29 20:24:32,753 [ERROR] KKT.router [ActiveMQ Session Task-57] | db927d80-a1d8-11ea-8ad7-525400aef612: KKT Interface: Unrecoverable Error: Please check ASAP: org.mule.api.service.FailedToQueueEventException: Interrupted while queueing event for "SEDA Stage com.KKT.router.requestGateway.stage1".
</code>```

答:
The issue seems to be that some error is triggering a redelivery of the message. When the redelivery count exceeds the maximum then you get a redelivery error.

You should get familiar with the JMS connector redelivery configuration: https://docs.mulesoft.com/mule-runtime/3.9/jms-transport-reference. Then check the Rollback Exception strategy https://docs.mulesoft.com/mule-runtime/3.9/rollback-exception-strategy on how you can handle those errors.

Note that ActiveMQ may have its own redelivery configurations.

Title: Mule exception strategy

Body:
On one particular queue alone the Mule JMS consumer count goes to 0 and comes back to default numbers after a point in time

My question is, why is it going down to 0 and I have message stuck in the queue? After few moments I find it comes back to 32 (default numberOfConcurrentTransactedRecievers) and processes the message and then again goes back to 0 consumers. What could be the problem?

I've other consumers in the same mule which are able to process cleanly without the count reducing.

My Configs:

<spring:bean id="domainConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory" lazy-init="true">
    <spring:property name="brokerURL" value="tcp://78.99.88.72:61616?jms.prefetchPolicy.all=2&jms.useAsyncSend=true&socketBufferSize=131072" />
    <spring:property name="redeliveryPolicy" ref="domainRedeliveryPolicy" />
</spring:bean>

<spring:bean id="amqExceptionConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory" lazy-init="true">
    <spring:property name="brokerURL" value="failover:(${domain.amq.failover.url}?jms.prefetchPolicy.all=2)" />
    <spring:property name="redeliveryPolicy" ref="domainRedeliveryPolicy" />
</spring:bean>

<jms:activemq-connector
    name="com.KKT.jmsConnector"
    username="${domain.amq.user.id}"
    password="${domain.amq.user.password}"
    connectionFactory-ref="pooledConnectionFactory"
    validateConnections="true"
    numberOfConcurrentTransactedReceivers="32"
    acknowledgementMode="AUTO_ACKNOWLEDGE"
    persistentDelivery="false"
    doc:name="AMQ Connector for KKTInterface"
    specification="1.1">
    <receiver-threading-profile maxThreadsActive="32" poolExhaustedAction="WAIT"/>
    <dispatcher-threading-profile maxThreadsActive="128" poolExhaustedAction="WAIT"/>
    <reconnect count="15" frequency="5000" blocking="true"/>
</jms:activemq-connector>

And I see the below error:

mule.log.5:2020-05-29 20:24:49,392 [ERROR] KKT.router [ActiveMQ Session Task-6] | ed938f60-a1d8-11ea-8ad7-525400aef612: KKT Interface: Unrecoverable Error: Please check ASAP: org.mule.transport.jms.redelivery.MessageRedeliveredException: "Message with id "ID:localhost-35511-1590775568949-1:1:162:1:3367" has been redelivered 1 times on endpoint "jms://com.KKT.router.inbox", which exceeds the maxRedelivery setting of 0 on the connector "com.KKT.router.jmsConnector".
mule.log.5:2020-05-29 20:24:49,216 [ERROR] exception.CatchMessagingExceptionStrategy [ActiveMQ Session Task-5] |
mule.log.5:2020-05-29 20:24:49,216 [ERROR] exception.CatchMessagingExceptionStrategy [ActiveMQ Session Task-4] |
mule.log.9:2020-05-29 20:24:32,753 [ERROR] exception.CatchMessagingExceptionStrategy [ActiveMQ Session Task-57] |
mule.log.9:2020-05-29 20:24:32,753 [ERROR] KKT.router [ActiveMQ Session Task-57] | db927d80-a1d8-11ea-8ad7-525400aef612: KKT Interface: Unrecoverable Error: Please check ASAP: org.mule.api.service.FailedToQueueEventException: Interrupted while queueing event for "SEDA Stage com.KKT.router.requestGateway.stage1".


问:
Jmeter can't download large file with http raw request or http request
target:

simulator 10 users download the file from the server

the file size   more than 300M

use HTTP request sampler to download file on the    Nginx server with
bean shell script.

result:

success 2/10

jmeter log :java.lang.OutOfMemoryError: Java heap space

configure in jmeter.bat:

set HEAP=-Xms1024m -Xmx3072m

set NEW=-XX:NewSize=512m   -XX:MaxNewSize=1024m

please help, thanks.

bean shell script

```<code>   import java.io.*;

   byte[] result=prev.getResponseData();
   String file_name="d:\\update.txt";
   String key=vars.get("name");
   String newname=file_name+key;
   File file=new File(newname);
   FileOutputStream out=new FileOutputStream(file);
   out.write(result);
   out.close();
</code>```

答:
If you have 10 concurrent downloads of the file which is more than 300 megabytes you will need at least 4 GB of heap space in order to fit everything (and looking into your "code" it would rather be around 10 GB), if it's not enough measure heap usage for 1 user and 2 users using i.e. JVisualVM and extrapolate it for 10 users

Don't use Beanshell for scripting

If you need to save response to the local drive it's better to go for Save Responses to a file listener, check out Performance Testing: Upload and Download Scenarios with Apache JMeter for more details if needed

Body:
target:

simulator 10 users download the file from the server

the file size   more than 300M

use HTTP request sampler to download file on the    Nginx server with
bean shell script.

result:

success 2/10

jmeter log :java.lang.OutOfMemoryError: Java heap space

configure in jmeter.bat:

set HEAP=-Xms1024m -Xmx3072m

set NEW=-XX:NewSize=512m   -XX:MaxNewSize=1024m

please help, thanks.

bean shell script

   import java.io.*;

   byte[] result=prev.getResponseData();
   String file_name="d:\\update.txt";
   String key=vars.get("name");
   String newname=file_name+key;
   File file=new File(newname);
   FileOutputStream out=new FileOutputStream(file);
   out.write(result);
   out.close();


问:
Send huge data bytes approx 1000 MB from Module A to Module B in Azure IoT Edge
I need to send a huge data bytes approx 1000 MB from Module A to Module B in Azure IoT Edge. (Module A and Module B are in same edge device)
Message Routes allows max 262143 bytes and Direct method allows approx 160 KB. Is there any other options to send huge data bytes between modules, Performance is a primary concern and I do not want to split the data and send it as a chunks.

Thanks

答: What are these data used for? Another option I can think of is to share data using docker volume, https://docs.docker.com/storage/volumes/ or bind mounts, https://docs.docker.com/storage/bind-mounts/.</p>


问:
Share Links on LinkedIn like Twitter
I need some links on my page to be shared on Facebook, Google Plus, LinkedIn and Twitter.
My links look something like this: http://www.example.com/subdomain?key1=val1&key2=val2&key3=val3

Almost in all of the cases the shared URL looks like this: http://www.example.com/subdomain?key1=val1

All the keys and values after the first & are removed.
Example URL Generation Code

```<code><a href="http://www.linkedin.com/shareArticle?mini=true&url=~$requestedUrl|escape:'url'`" title="Share this on Linkedin" target="_new" class="lin"></a>
</code>```

This leads to the following:

```<code><a href="http://www.linkedin.com/shareArticle?mini=true&url=http://www.example.com/subdomain?key1=val1&key2=val2&key3=val3" title="Share this on Linkedin" target="_new" class="lin"></a>
</code>```

The $requestedUrl is sent from my PHP and will remain common to be shared across facebook, gplus, linkedin and twitter.

答:
Take a quick glance at your full URL...

```<code><a href="http://www.linkedin.com/shareArticle?mini=true&url=http://www.example.com/subdomain?key1=val1&key2=val2&key3=val3" title="Share this on Linkedin" target="_new" class="lin"></a>
</code>```

So, you DID escape the &!  BUT!  You used HTML-escaping.  What you need is URL-escaping.  They are very, very different.

& turns into & with HTML escaping.  But & turns into %26 with URL-encoding.  So, your code should be...

```<code><a href="http://www.linkedin.com/shareArticle?mini=true&url=http%3A%2F%2Fwww.example.com%2Fsubdomain%3Fkey1%3Dval1%26key2%3Dval2%26key3%3Dval3" title="Share this on Linkedin" target="_new" class="lin"></a>
</code>```

So, for example, I want to share this url: http://www.revoltlib.com/?id=17.  It has a ? in it, too!  This is the share URL result...

```<code>https://www.linkedin.com/sharing/share-offsite/?url=http%3A%2F%2Fwww.revoltlib.com%2F%3Fid%3D17
</code>```

Works for me:

Wherever you are defining or getting escape:'url' from, it appears to be doing the incorrect type of escaping entirely.

Title: Share Links on LinkedIn like Twitter

Body:
I need some links on my page to be shared on Facebook, Google Plus, LinkedIn and Twitter.
My links look something like this: http://www.example.com/subdomain?key1=val1&key2=val2&key3=val3

Almost in all of the cases the shared URL looks like this: http://www.example.com/subdomain?key1=val1

All the keys and values after the first & are removed.
Example URL Generation Code

This leads to the following:

The $requestedUrl is sent from my PHP and will remain common to be shared across facebook, gplus, linkedin and twitter.

Body:
Take a quick glance at your full URL...

<a href="http://www.linkedin.com/shareArticle?mini=true&url=http://www.example.com/subdomain?key1=val1&amp;key2=val2&amp;key3=val3" title="Share this on Linkedin" target="_new" class="lin"></a>

So, you DID escape the &!  BUT!  You used HTML-escaping.  What you need is URL-escaping.  They are very, very different.

& turns into &amp; with HTML escaping.  But & turns into %26 with URL-encoding.  So, your code should be...

<a href="http://www.linkedin.com/shareArticle?mini=true&url=http%3A%2F%2Fwww.example.com%2Fsubdomain%3Fkey1%3Dval1%26key2%3Dval2%26key3%3Dval3" title="Share this on Linkedin" target="_new" class="lin"></a>

So, for example, I want to share this url: http://www.revoltlib.com/?id=17.  It has a ? in it, too!  This is the share URL result...

https://www.linkedin.com/sharing/share-offsite/?url=http%3A%2F%2Fwww.revoltlib.com%2F%3Fid%3D17

Works for me:

Wherever you are defining or getting escape:'url' from, it appears to be doing the incorrect type of escaping entirely.


问:
Dart: Simultaneous http requests
Problem: Http.get requests in future functions are called one after the other.

```<code>//this should open 5 simultaneous http connections
for (var i= 0; i < 5; i++) {
  getImage('[image soure]', i);
}
</code>```

I've divided the method's code into several parts to better convey the problem.

```<code>import 'package:http/http.dart' as http;

void getImage(final String img, final int i) async {
  var blurHash = '';
  try {
    //PART: LOADING
    print('loading $img...');

    //PART: A
    var client = http.Client();

    var res = await client.get(img);

    print('$i: a');

    //PART: B
    var bbytes = res.bodyBytes;
    print('$i: b');

    //PART: C
    var l = bbytes.toList();
    print('$i: c');

    ...

    blurHash = '...';
  } catch (e) {
    print(e);
  }
}
</code>```

What the console output should look like:

```<code>loading img.png
loading img.png
loading img.png
loading img.png
loading img.png
0: a
1: a
2: a
3: a
4: a
0: b
1: b
2: b
3: b
4: b
0: c
1: c
2: c
3: c
4: c
</code>```

What the console output really look like:

```<code>loading img.png
loading img.png
loading img.png
loading img.png
loading img.png
0: a
0: b
0: c
1: a
1: b
1: c
2: a
2: b
2: c
3: a
3: b
3: c
4: a
4: b
4: c
</code>```

This means that the loading part is executed simultaneously but it seems like the http.get requests in Part A are executed behind each other.

答:
await someFuture (which as Christopher Moore explained in comments) is syntactic sugar for return someFuture.then(...).  Execution from your function cannot yield unless it returns/awaits.

You can explicitly allow your functions to yield by sprinkling in some await null lines; that should allow your getImage calls to be interleaved in the way that you desire.  Note that doing so will not make things any faster; each Dart isolate executes Dart code in a single thread, so if you're not awaiting an asynchronous operation whose underlying implementation involves another isolate or thread, you won't be saving any time overall.  Adding extra awaits instead would introduce more context switching and make everything take a bit longer. (That still could be useful if your code needs to respond to other events while doing expensive operations, though.)

Title: Dart: Simultaneous http requests

Body:
Problem: Http.get requests in future functions are called one after the other.

//this should open 5 simultaneous http connections
for (var i= 0; i < 5; i++) {
  getImage('[image soure]', i);
}

I've divided the method's code into several parts to better convey the problem.

import 'package:http/http.dart' as http;

void getImage(final String img, final int i) async {
  var blurHash = '';
  try {
    //PART: LOADING
    print('loading $img...');

    //PART: A
    var client = http.Client();

    var res = await client.get(img);

    print('$i: a');

    //PART: B
    var bbytes = res.bodyBytes;
    print('$i: b');

    //PART: C
    var l = bbytes.toList();
    print('$i: c');

    ...

    blurHash = '...';
  } catch (e) {
    print(e);
  }
}

What the console output should look like:

loading img.png
loading img.png
loading img.png
loading img.png
loading img.png
0: a
1: a
2: a
3: a
4: a
0: b
1: b
2: b
3: b
4: b
0: c
1: c
2: c
3: c
4: c

What the console output really look like:

loading img.png
loading img.png
loading img.png
loading img.png
loading img.png
0: a
0: b
0: c
1: a
1: b
1: c
2: a
2: b
2: c
3: a
3: b
3: c
4: a
4: b
4: c

This means that the loading part is executed simultaneously but it seems like the http.get requests in Part A are executed behind each other.


问:
Create a .NET subapplication with different version than parent
I have a website configured in .NET 2.0, and I cannot change it because of compatibility problems. Inside that website, I have other website in 4.0. So let's think something like this:

```<code>RootWebsite --> 2.0

 - Default.aspx
 - Another.aspx
 - PROMOS
     - AnotherWebsite --> 4.0
         -web.config
 - web.config
</code>```

Well, the AnotherWbesite (4.0) is using some libraries that don't work on 2.0. I don't know why, but when I execute the website, it is executing in 2.0 instead of 4.0, although it has its own web.config and it is configured in 4.0.

Is there any way to force the AnotherWebSite to execute in 4.0, despite its father is in 2.0?

Thank you very much

答:
I have found the solution:

in the parent's web.config, you have to wrap the "system.web" section into the following:

```<code><location path="." inheritInChildApplications="false">
  <system.web>
    <!-- ... -->
  </system.web>
</location>
</code>```

This way, the children  won't inherits anything from the parent, so you can use different .NET versions.

Body:
I have a website configured in .NET 2.0, and I cannot change it because of compatibility problems. Inside that website, I have other website in 4.0. So let's think something like this:

RootWebsite --> 2.0

 - Default.aspx
 - Another.aspx
 - PROMOS
     - AnotherWebsite --> 4.0
         -web.config
 - web.config

Well, the AnotherWbesite (4.0) is using some libraries that don't work on 2.0. I don't know why, but when I execute the website, it is executing in 2.0 instead of 4.0, although it has its own web.config and it is configured in 4.0.

Is there any way to force the AnotherWebSite to execute in 4.0, despite its father is in 2.0?

Thank you very much

Body:
I have found the solution:

in the parent's web.config, you have to wrap the "system.web" section into the following:

<location path="." inheritInChildApplications="false">
  <system.web>
    <!-- ... -->
  </system.web>
</location>

This way, the children  won't inherits anything from the parent, so you can use different .NET versions.


问:
Horizontal
 list doesn't take entire width of it's children
 elements
I have horizontal unordered list with 9
 items total. Every
 item has width of 342px(width defined based on  element inside the list). All images has the same width, and every
 element has margin-left: 10px.

```<code><ul class="carousel" role="list" style="left: 0px;">
   <li class="carousel-card" aria-posinset="1" aria-hidden="false" role="listitem" aria-setsize="9" style="display: inline-block;">
      <span class="a-list-item">
         <div data-reference-url="Url" data-reference-title="Title" class="data-item">
            <a class="carousel-item" target="" rel="noopener" href="link">
               <div class="image">
                  <img alt="image" src="myUrl" height="192px" width="342px">
                  <div class="someClass">...</div>
               </div>
            </a>
         </div>
      </span>
   </li>
   <li class="carousel-card" aria-posinset="2" aria-hidden="false" role="listitem" aria-setsize="9" style="display: inline-block;">
      <span class="a-list-item">
         <div data-reference-url="Url" data-reference-title="Title" class="data-item">
            <a class="carousel-item" target="" rel="noopener" href="link">
               <div class="image">
                  <img alt="image" src="myUrl" height="192px" width="342px">
                  <div class="someClass">...</div>
               </div>
            </a>
         </div>
      </span>
   </li>
   ....
</ul>
</code>```

Even though I have 9 items in the list, I see that for some reason, entire width of
 element is always no more than 1385 px. While I expect it to be:

9[items in the list]*(342px[width of
)] + 10px [margin of
]) = 3168 px.

I inspected all li elements, and confirmed that their width is correct and is always 342px for every element. What can be the reason why
 width is not equal to the width of all li elements that are inside of
?

My CSS styles:

```<code>.carousel {
    display: inline-block;
    position: relative;
    left: 0px;
    margin: 0px 0px 14px;
    padding: 0px;
    display: table;
    content: "";
    line-height: 0;
    font-size: 0;

}

.carousel-card {
    display: inline-block;
    margin: 0 10px 0 0;
    position: relative;
    overflow: hidden;
    text-align: center;
    min-width: 145px;
    vertical-align: top;
    min-height: 200px;
    max-width: unset !important;
    max-height: unset !important;
 }

.a-list-item {
    text-align: center;
    position: relative;
    display: inline-block;
    min-width: 145px;
}
</code>```

答: The calculated ul width is not based on the content of the li. Content can overflow the container it is in. You have to specify the width of the li elements. At first glance the outcome seems based on the min-width of the elements.</p>

Title: Horizontal <ul> list doesn't take entire width of it's children <li> elements

Body:
I have horizontal unordered list with 9
 items total. Every
 item has width of 342px(width defined based on  element inside the list). All images has the same width, and every
 element has margin-left: 10px.

...

...

   ....

Even though I have 9 items in the list, I see that for some reason, entire width of
 element is always no more than 1385 px. While I expect it to be:

9[items in the list]*(342px[width of
)] + 10px [margin of
]) = 3168 px.

I inspected all li elements, and confirmed that their width is correct and is always 342px for every element. What can be the reason why
 width is not equal to the width of all li elements that are inside of
?

My CSS styles:

.carousel {
    display: inline-block;
    position: relative;
    left: 0px;
    margin: 0px 0px 14px;
    padding: 0px;
    display: table;
    content: "";
    line-height: 0;
    font-size: 0;

}

.carousel-card {
    display: inline-block;
    margin: 0 10px 0 0;
    position: relative;
    overflow: hidden;
    text-align: center;
    min-width: 145px;
    vertical-align: top;
    min-height: 200px;
    max-width: unset !important;
    max-height: unset !important;
 }

.a-list-item {
    text-align: center;
    position: relative;
    display: inline-block;
    min-width: 145px;
}


问:
Bootstrap 4 put items underneath each other flex box
I wrote the following code: </p>

```<code><div class="row d-flex h-100">
    <div class="col-4 d-flex align-self-center justify-content-center text-center">
        <img class="flex-item" src="https://image.com"/>
        <br/>
        <h2 class="flex-item mat-display-1">Ajax</h2>
    </div>
</div>
</code>```

<p>I want to align the items within the column underneath each other instead of next to eachother, but I don't seem to be able to do it somehow. How can I achieve this behaviour? </p>

答:
Consider adding flex-column class to parent div

```<code><div class="row d-flex flex-column h-100">
    <div class="col-4 d-flex align-self-center justify-content-center text-center">
        <img class="flex-item" src="https://image.com"/>
        <br/>
        <h2 class="flex-item mat-display-1">Ajax</h2>
    </div>
</div>
</code>```

Body:
I wrote the following code:

Ajax

I want to align the items within the column underneath each other instead of next to eachother, but I don't seem to be able to do it somehow. How can I achieve this behaviour?

Body:
Consider adding flex-column class to parent div

<div class="row d-flex flex-column h-100">
    <div class="col-4 d-flex align-self-center justify-content-center text-center">
        <img class="flex-item" src="https://image.com"/>
        <br/>
        <h2 class="flex-item mat-display-1">Ajax</h2>
    </div>
</div>


问:
jQuery form Submit not working in JSF?
I have a JSf form, I am tryin' to use jQuery Ui dialog plugin to submit the form.
here's the code snippet.

```<code>function confirmSubmit() {
          $('#dialog').dialog('open');
          return false;
      }

    $('#dialog').dialog({
        autoOpen : false,
        width : 400,
        modal : true,
        resizable : false,
        buttons : {
            "Submit Form" : function() {
                 document.myForm.submit();
            },
            "Cancel" : function() {
                $(this).dialog("close");
            }
        }
    });
<h:form id="myForm">
<h:commandLink action="#{Bean.search}" type="submit" onclick="return confirmSubmit()"   id="search" styleClass="buttonSearch">
                 </h:commandLink>
</code>```

The "document.myForm.submit();" part in the dialog box isn't working i.e., no calls goes to the server and in the server console I see the error:

11:45:32,738 SEVERE [lifecycle]
  JSF1054: (Phase ID: RENDER_RESPONSE 6,
  View ID: /PRT01/IMCM0101.jsp)
  Exception thrown during phase
  execution:
  javax.faces.event.PhaseEvent[source=com.sun.faces.lifecycle.LifecycleImpl@ec333b]

The dialog box is appearing correctly but once i press the submit button "document.myForm.submit();" code is executed and the form is NOT submitted instead the above described error comes on the server console.

答:
It's done, some JSF parameters were missing. which jsf adds during form submissiom, I added them using jQuery:</p>

```<code>$("a[id$='search']").click(function() {
    var input = $("<input>").attr("type", "hidden").attr("name",   "myForm:search").val("myForm:search");
    $('#myForm').append($(input));
    $("p#dialog-email").html(titleVar);
    $('#dialog').dialog('open');
});
</code>```

Title: jQuery form Submit not working in JSF?

Body:
I have a JSf form, I am tryin' to use jQuery Ui dialog plugin to submit the form.
here's the code snippet.

function confirmSubmit() {
          $('#dialog').dialog('open');
          return false;
      }

    $('#dialog').dialog({
        autoOpen : false,
        width : 400,
        modal : true,
        resizable : false,
        buttons : {
            "Submit Form" : function() {
                 document.myForm.submit();
            },
            "Cancel" : function() {
                $(this).dialog("close");
            }
        }
    });
<h:form id="myForm">
<h:commandLink action="#{Bean.search}" type="submit" onclick="return confirmSubmit()"   id="search" styleClass="buttonSearch">
                 </h:commandLink>

The "document.myForm.submit();" part in the dialog box isn't working i.e., no calls goes to the server and in the server console I see the error:

11:45:32,738 SEVERE [lifecycle]
  JSF1054: (Phase ID: RENDER_RESPONSE 6,
  View ID: /PRT01/IMCM0101.jsp)
  Exception thrown during phase
  execution:
  javax.faces.event.PhaseEvent[source=com.sun.faces.lifecycle.LifecycleImpl@ec333b]

The dialog box is appearing correctly but once i press the submit button "document.myForm.submit();" code is executed and the form is NOT submitted instead the above described error comes on the server console.

Body:
It's done, some JSF parameters were missing. which jsf adds during form submissiom, I added them using jQuery:

$("a[id$='search']").click(function() {
    var input = $("<input>").attr("type", "hidden").attr("name",   "myForm:search").val("myForm:search");
    $('#myForm').append($(input));
    $("p#dialog-email").html(titleVar);
    $('#dialog').dialog('open');
});


问:
Return the value from a checklist on a UserForm
This makes a UserForm checklist and it works.

```<code>Sub UserForm_Initialize()

Dim LastRow     As Long
Dim i           As Long
Dim chkBox      As MSForms.CheckBox

LastRow = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

For i = 1 To LastRow
    Set chkBox = Me.Controls.Add("Forms.CheckBox.1", "CheckBox_" & i)
    chkBox.Caption = Worksheets("Sheet1").Cells(i, 1).Value
    chkBox.Left = 5
    chkBox.Top = 5 + ((i - 1) * 20)
Next i

End Sub
</code>```

I want to select as many of the boxes as I need, hit a command button and have the resulting values pasted in a different cell.

For example I have 1-10 in cells A1-A10. The first piece makes a checklist for each value 1-10. If I check the boxes next to 2, 3, 5, and 7, hit the command button and then want 2, 3, 5, and 7 to be entered into cells G2, G3, G5 and G7.

I cant figure out how to get this last part to happen. I have tried to make If statement

```<code>Sub CommandButton1_Click()
    If chkBox1 = False Then GoTo Here
    Else
        Range("G1").Value = Me.TextBox1.Text
    End If
    Here
End Sub
</code>```

I get

"Compile error: Variable not defined"

I tried different names instead of "chkbox1" but get the same error.

答:
I think this does what you want.

You can reference the controls using their name and loop through them in a similar way to the Initialize code. By declaring 'LastRow` before the sub we can use it in both subs.

```<code>Dim LastRow     As Long

Private Sub CommandButton1_Click()

Dim i As Long

For i = 1 To LastRow
    If Me.Controls("CheckBox_" & i) Then
        Range("G" & i).Value = i
    End If
Next i

End Sub

Sub UserForm_Initialize()

Dim i           As Long
Dim chkBox      As MSForms.CheckBox

LastRow = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

For i = 1 To LastRow
    Set chkBox = Me.Controls.Add("Forms.CheckBox.1", "CheckBox_" & i)
    chkBox.Caption = Worksheets("Sheet1").Cells(i, 1).Value
    chkBox.Left = 5
    chkBox.Top = 5 + ((i - 1) * 20)
Next i

End Sub
</code>```

Body:
This makes a UserForm checklist and it works.

Sub UserForm_Initialize()

Dim LastRow     As Long
Dim i           As Long
Dim chkBox      As MSForms.CheckBox

LastRow = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

For i = 1 To LastRow
    Set chkBox = Me.Controls.Add("Forms.CheckBox.1", "CheckBox_" & i)
    chkBox.Caption = Worksheets("Sheet1").Cells(i, 1).Value
    chkBox.Left = 5
    chkBox.Top = 5 + ((i - 1) * 20)
Next i

End Sub

I want to select as many of the boxes as I need, hit a command button and have the resulting values pasted in a different cell.

For example I have 1-10 in cells A1-A10. The first piece makes a checklist for each value 1-10. If I check the boxes next to 2, 3, 5, and 7, hit the command button and then want 2, 3, 5, and 7 to be entered into cells G2, G3, G5 and G7.

I cant figure out how to get this last part to happen. I have tried to make If statement

Sub CommandButton1_Click()
    If chkBox1 = False Then GoTo Here
    Else
        Range("G1").Value = Me.TextBox1.Text
    End If
    Here
End Sub

I get

"Compile error: Variable not defined"

I tried different names instead of "chkbox1" but get the same error.

Body:
I think this does what you want.

You can reference the controls using their name and loop through them in a similar way to the Initialize code. By declaring 'LastRow` before the sub we can use it in both subs.

Dim LastRow     As Long

Private Sub CommandButton1_Click()

Dim i As Long

For i = 1 To LastRow
    If Me.Controls("CheckBox_" & i) Then
        Range("G" & i).Value = i
    End If
Next i

End Sub

Sub UserForm_Initialize()

Dim i           As Long
Dim chkBox      As MSForms.CheckBox

LastRow = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

For i = 1 To LastRow
    Set chkBox = Me.Controls.Add("Forms.CheckBox.1", "CheckBox_" & i)
    chkBox.Caption = Worksheets("Sheet1").Cells(i, 1).Value
    chkBox.Left = 5
    chkBox.Top = 5 + ((i - 1) * 20)
Next i

End Sub


问:
Setting up curl library path in cmake
I downloaded "curl library" for use with a third party application. When I run the included cmake file, I get the following error. Please help me. I appreciate it:

```<code>> The C compiler identification is MSVC 18.0.30501.0
    >     The CXX compiler identification is MSVC 18.0.30501.0
    >     Check for working C compiler using: Visual Studio 12 2013
    >     Check for working C compiler using: Visual Studio 12 2013 -- works
    >     Detecting C compiler ABI info
    >     Detecting C compiler ABI info - done
    >     Check for working CXX compiler using: Visual Studio 12 2013
    >     Check for working CXX compiler using: Visual Studio 12 2013 -- works
    >     Detecting CXX compiler ABI info
    >     Detecting CXX compiler ABI info - done
    >     Could NOT find CURL (missing:  CURL_LIBRARY) (found version "7.38.0")
    >     CMake Error at CMakeLists.txt:49 (MESSAGE):
    >       Could not find the CURL library and development files.
    >
    >     Configuring incomplete, errors occurred!
    >     See also "C:/BUILD/CMakeFiles/CMakeOutput.log".
</code>```

I set environment variable for "CURL_LIBRARY" in Windows to point to the location of the installation of library files for curl, but cmake can't still find it even though it indicates that version 7.38.0 was detected on my system.

Thanks for the help..

EDIT:
cMakeLists.txt file

```<code>  ...
# Look for required libraries
SET(requiredlibs)

FIND_PACKAGE(CURL)
IF(CURL_FOUND)
  INCLUDE_DIRECTORIES(${CURL_INCLUDE_DIR})
  SET(requiredlibs ${requiredlibs} ${CURL_LIBRARIES} )
ELSE(CURL_FOUND)
  MESSAGE(FATAL_ERROR "Could not find the CURL library and development files.")
ENDIF(CURL_FOUND)
   ...
</code>```

I set the include and lib dirs in Windows Environment Variable, but no change.

EDIT:
this is complete project file: cmake project.

答:
via pkgconfig</p>

```<code>include(FindPkgConfig)
pkg_check_modules(CURL libcurl REQUIRED)
include_directories(
  SYSTEM ${CURL_INCLUDE_DIRS}
)
target_link_libraries(YOURTARGETNAME
  ${CURL_LIBRARIES}
)
</code>```

Title: Setting up curl library path in cmake

Body:
I downloaded "curl library" for use with a third party application. When I run the included cmake file, I get the following error. Please help me. I appreciate it:

> The C compiler identification is MSVC 18.0.30501.0
    >     The CXX compiler identification is MSVC 18.0.30501.0
    >     Check for working C compiler using: Visual Studio 12 2013
    >     Check for working C compiler using: Visual Studio 12 2013 -- works
    >     Detecting C compiler ABI info
    >     Detecting C compiler ABI info - done
    >     Check for working CXX compiler using: Visual Studio 12 2013
    >     Check for working CXX compiler using: Visual Studio 12 2013 -- works
    >     Detecting CXX compiler ABI info
    >     Detecting CXX compiler ABI info - done
    >     Could NOT find CURL (missing:  CURL_LIBRARY) (found version "7.38.0")
    >     CMake Error at CMakeLists.txt:49 (MESSAGE):
    >       Could not find the CURL library and development files.
    >
    >     Configuring incomplete, errors occurred!
    >     See also "C:/BUILD/CMakeFiles/CMakeOutput.log".

I set environment variable for "CURL_LIBRARY" in Windows to point to the location of the installation of library files for curl, but cmake can't still find it even though it indicates that version 7.38.0 was detected on my system.

Thanks for the help..

EDIT:
cMakeLists.txt file

  ...
# Look for required libraries
SET(requiredlibs)

FIND_PACKAGE(CURL)
IF(CURL_FOUND)
  INCLUDE_DIRECTORIES(${CURL_INCLUDE_DIR})
  SET(requiredlibs ${requiredlibs} ${CURL_LIBRARIES} )
ELSE(CURL_FOUND)
  MESSAGE(FATAL_ERROR "Could not find the CURL library and development files.")
ENDIF(CURL_FOUND)
   ...

I set the include and lib dirs in Windows Environment Variable, but no change.

EDIT:
this is complete project file: cmake project.

Body:
via pkgconfig

include(FindPkgConfig)
pkg_check_modules(CURL libcurl REQUIRED)
include_directories(
  SYSTEM ${CURL_INCLUDE_DIRS}
)
target_link_libraries(YOURTARGETNAME
  ${CURL_LIBRARIES}
)


问:
How to implement a generic DAO with the same Entity Manager in java EE 8
I'm a begginer in Java EE and in JPA. In the past I have been creating a simple web-project, and I have implemented a generci DAO pattern without CDI, handling the Enitiry Manager.I know that diffrent EntityManager can use the same persistent context but because persistent context is a black box for me, I inject in the DAO constractor one EntityManager passing it as argument.I use this aproach for two reasons:

Seperate the operation that has to do with diffrent
entites.

Deal with concurrency problems because all
operation will be handeld in the same EntityManager and
Trasanction

Here is the code of generic DAO:

GenericDAO

```<code>import java.util.List ;
import javax.persistence.EntityManager ;
import javax.persistence.Query ;

public abstract class GenericDAO<T> {

    protected final Class<T> persistentClass;
    protected final EntityManager em;

    public GenericDAO(EntityManager em, Class<T> persistencClass) {
        this.persistentClass = persistencClass;
        this.em = em;
    }

    public List<T> find(int id) {
        List<T> list;
        Query query = em.createQuery("select e from " + persistentClass.getSimpleName() + " e" + " where e.id =:id").setParameter("id", id);
        list = query.getResultList();
        return list;
    }

    public List<T> findAll() {
        List<T> list;
        Query query = em.createQuery("select e from " + persistentClass.getSimpleName() + " e");
        list = query.getResultList();
        return list;
    }

    public void create(T entity) {
        em.persist(entity);
    }

    public void edit(T entity) {
        em.merge(entity);
    }

    public void remove(T entity) {
        em.remove(em.merge(entity));
    }
}
</code>```

Actual implementation of generic DAO, code below:

UserDAOImpl

```<code>import java.util.List;
import entities.User;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class UserDAOImpl extends GenericDAO<User> {
     public UserDAOImpl(EntityManager em) {
           super(em, User.class);
     }
}
</code>```

TagDAOImpl

```<code>import entities.Tag ;
import java.util.List ;
import javax.persistence.EntityManager ;
import javax.persistence.Query ;

public class TagDAOImpl extends GenericDAO<Tag> {

    public TagDAOImpl(EntityManager em) {
        super(em, Tag.class);
    }
}
</code>```

Now I want to implement the same pattern using Java EE injection of EntityManager. After a good search I  found out the same solution like the below:

GenericDAO In Java ee

```<code>    public abstract class BaseDAO<T extends AbstractEntity> {

    private Class<T> entityClass() {
        @SuppressWarnings("unchecked")
        ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();
        return (Class<T>) parameterizedType.getActualTypeArguments()[0];
    }

    protected abstract EntityManager entityManager();

    private final String SELECT_ALL = "SELECT e FROM ";
    private final String SELECT_COUNT = "SELECT COUNT(e) FROM ";
    private final String INSTANCE = " e";

    public List<T> findAll() {
        return entityManager()
                .createQuery(SELECT_ALL + entityClass().getSimpleName() + INSTANCE)
                .getResultList();
    }

    public Long count() {
        Object resulet = entityManager()
                .createQuery(SELECT_COUNT + entityClass().getSimpleName() + INSTANCE)
                .getSingleResult();
        return (Long) resulet;
    }
}
</code>```

Actual implementation of generic DAO in Java ee, code below:

UserDAO

```<code>@Stateless
public class UserDAO extends BaseDAO<User> {

    @Inject
    protected EntityManager entityManger;

    @Override
    protected EntityManager entityManager() {
        return this.entityManger;
    }
}
</code>```

TagDAO

```<code>@Stateless
public class TagDAO extends BaseDAO<Tag> {

    @Inject
    protected EntityManager entityManger;

    @Override
    protected EntityManager entityManager() {
        return this.entityManger;
    }

}
</code>```

My problem here is that if I inject EntityManager in UserDAO and TagDAO, I have two diffrent instances of EntityManager. Will this be a problem if I want to persist a user and update a tag? Can I have such an example? Including the advantages and disadvantages.

答:
First of all, you may add the @Inject private EntityManager into your GenericDAO class, applying DRY concepts.
The usage of EntityManager and it's uniqueness will depend mainly of the scope chosen on you production methods. If you are sure all requests will be handled in a @RequestScoped environment, you may produce the EntityManager with this scope and all your DAOs will share the same bean as long they are at the same request.

To produce a EntityManager with a request scope, you may use a CDI bean and a producer field or method, such as:

```<code>@ApplicationScoped
public class EntityManagerProducer implements Serializable {

    @Produces
    @RequestScoped
    // @MyBusinessDatabase // A qualifier so you can select different databases
    @PersistenceContext
    private EntityManager entityManager;

}
</code>```

You may also use a @Dependent pseudo-scope. In this case, each entityManager injected will be unique to the injected bean. Please check this and this. As EntityManager is a lightweight entity (when opposed to an EntityManagerFactory), there is little overhead in using such scope, and we have, as an advantage when compared to @RequestScoped beans, the possibility to use the same bean in non-request operations, such as asynchronous or automated server-side calls.

I've been using @Depended scoped entity managers for quite some time now, with different JPA implementations (Eclipselink and OpenJPA) without any issues but the ordinary optimistic lock exception when one given entity instance is updated by too many threads at the same time. When the case is critical, you may use a pessimistic approach to handle these cases.

Body:
I'm a begginer in Java EE and in JPA. In the past I have been creating a simple web-project, and I have implemented a generci DAO pattern without CDI, handling the Enitiry Manager.I know that diffrent EntityManager can use the same persistent context but because persistent context is a black box for me, I inject in the DAO constractor one EntityManager passing it as argument.I use this aproach for two reasons:

Seperate the operation that has to do with diffrent
entites.

Deal with concurrency problems because all
operation will be handeld in the same EntityManager and
Trasanction

Here is the code of generic DAO:

GenericDAO

import java.util.List ;
import javax.persistence.EntityManager ;
import javax.persistence.Query ;

public abstract class GenericDAO<T> {

    protected final Class<T> persistentClass;
    protected final EntityManager em;

    public GenericDAO(EntityManager em, Class<T> persistencClass) {
        this.persistentClass = persistencClass;
        this.em = em;
    }

    public List<T> find(int id) {
        List<T> list;
        Query query = em.createQuery("select e from " + persistentClass.getSimpleName() + " e" + " where e.id =:id").setParameter("id", id);
        list = query.getResultList();
        return list;
    }

    public List<T> findAll() {
        List<T> list;
        Query query = em.createQuery("select e from " + persistentClass.getSimpleName() + " e");
        list = query.getResultList();
        return list;
    }

    public void create(T entity) {
        em.persist(entity);
    }

    public void edit(T entity) {
        em.merge(entity);
    }

    public void remove(T entity) {
        em.remove(em.merge(entity));
    }
}

Actual implementation of generic DAO, code below:

UserDAOImpl

import java.util.List;
import entities.User;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class UserDAOImpl extends GenericDAO<User> {
     public UserDAOImpl(EntityManager em) {
           super(em, User.class);
     }
}

TagDAOImpl

import entities.Tag ;
import java.util.List ;
import javax.persistence.EntityManager ;
import javax.persistence.Query ;

public class TagDAOImpl extends GenericDAO<Tag> {

    public TagDAOImpl(EntityManager em) {
        super(em, Tag.class);
    }
}

Now I want to implement the same pattern using Java EE injection of EntityManager. After a good search I  found out the same solution like the below:

GenericDAO In Java ee

    public abstract class BaseDAO<T extends AbstractEntity> {

    private Class<T> entityClass() {
        @SuppressWarnings("unchecked")
        ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();
        return (Class<T>) parameterizedType.getActualTypeArguments()[0];
    }

    protected abstract EntityManager entityManager();

    private final String SELECT_ALL = "SELECT e FROM ";
    private final String SELECT_COUNT = "SELECT COUNT(e) FROM ";
    private final String INSTANCE = " e";

    public List<T> findAll() {
        return entityManager()
                .createQuery(SELECT_ALL + entityClass().getSimpleName() + INSTANCE)
                .getResultList();
    }

    public Long count() {
        Object resulet = entityManager()
                .createQuery(SELECT_COUNT + entityClass().getSimpleName() + INSTANCE)
                .getSingleResult();
        return (Long) resulet;
    }
}

Actual implementation of generic DAO in Java ee, code below:

UserDAO

@Stateless
public class UserDAO extends BaseDAO<User> {

    @Inject
    protected EntityManager entityManger;

    @Override
    protected EntityManager entityManager() {
        return this.entityManger;
    }
}

TagDAO

@Stateless
public class TagDAO extends BaseDAO<Tag> {

    @Inject
    protected EntityManager entityManger;

    @Override
    protected EntityManager entityManager() {
        return this.entityManger;
    }

}

My problem here is that if I inject EntityManager in UserDAO and TagDAO, I have two diffrent instances of EntityManager. Will this be a problem if I want to persist a user and update a tag? Can I have such an example? Including the advantages and disadvantages.

Body:
First of all, you may add the @Inject private EntityManager into your GenericDAO class, applying DRY concepts.
The usage of EntityManager and it's uniqueness will depend mainly of the scope chosen on you production methods. If you are sure all requests will be handled in a @RequestScoped environment, you may produce the EntityManager with this scope and all your DAOs will share the same bean as long they are at the same request.

To produce a EntityManager with a request scope, you may use a CDI bean and a producer field or method, such as:

@ApplicationScoped
public class EntityManagerProducer implements Serializable {

    @Produces
    @RequestScoped
    // @MyBusinessDatabase // A qualifier so you can select different databases
    @PersistenceContext
    private EntityManager entityManager;

}

You may also use a @Dependent pseudo-scope. In this case, each entityManager injected will be unique to the injected bean. Please check this and this. As EntityManager is a lightweight entity (when opposed to an EntityManagerFactory), there is little overhead in using such scope, and we have, as an advantage when compared to @RequestScoped beans, the possibility to use the same bean in non-request operations, such as asynchronous or automated server-side calls.

I've been using @Depended scoped entity managers for quite some time now, with different JPA implementations (Eclipselink and OpenJPA) without any issues but the ordinary optimistic lock exception when one given entity instance is updated by too many threads at the same time. When the case is critical, you may use a pessimistic approach to handle these cases.


问:
Creating POJOs for json with single field containing Array with RestTemplate
I am creating a client for the following format of JSON -

```<code>{
    "results": [
        {
            "Product": "K265113",
            "Language": "EN",
            "LongText": "FIXTURE,INTERIOR,WALL"
        }
    ]
}
</code>```

The JSON always contains "results" field which is an array of a single element (it will always be a single element in this array). I just need LongText field from the JSON and nothing else. I am using Spring RESTTemplate.

I know that it works if I create two DTOs like -

```<code>public class ParentDTO
{
    private List<ChildDTO> results;

    public List<ChildDTO> getResults()
    {
        return results;
    }

    public void setResults(List<ChildDTO> results)
    {
        this.results = results;
    }
}

public class ChildDTO
{
    private String longText;

    public String getLongText()
    {
        return longText;
    }

    @JsonProperty("LongText")
    public void setLongText(String longText)
    {
        this.longText = longText;
    }
}
</code>```

But is there any way to read longText by creating a single DTO as the parent DTO is not having any useful field as I know there will always but just one element in the results array.

答:
The reason you need only single DTO could be that you want only single class to perform this task. You can achieve that using ChildDTO as inner class which will make it more readable and maintainable.

The other way is to not parse the spring template response into DTOs instead use JSONNode class of Jackson databind API.

```<code>JsonNode root = objectMapper.readTree(response.getBody());
</code>```

You can find more information at
https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/JsonNode.html

You can traverse down the tree and could retrieve the value of the attribute directly without any DTOs.

Body:
I am creating a client for the following format of JSON -

{
    "results": [
        {
            "Product": "K265113",
            "Language": "EN",
            "LongText": "FIXTURE,INTERIOR,WALL"
        }
    ]
}

The JSON always contains "results" field which is an array of a single element (it will always be a single element in this array). I just need LongText field from the JSON and nothing else. I am using Spring RESTTemplate.

I know that it works if I create two DTOs like -

public class ParentDTO
{
    private List<ChildDTO> results;

    public List<ChildDTO> getResults()
    {
        return results;
    }

    public void setResults(List<ChildDTO> results)
    {
        this.results = results;
    }
}

public class ChildDTO
{
    private String longText;

    public String getLongText()
    {
        return longText;
    }

    @JsonProperty("LongText")
    public void setLongText(String longText)
    {
        this.longText = longText;
    }
}

But is there any way to read longText by creating a single DTO as the parent DTO is not having any useful field as I know there will always but just one element in the results array.

Body:
The reason you need only single DTO could be that you want only single class to perform this task. You can achieve that using ChildDTO as inner class which will make it more readable and maintainable.

The other way is to not parse the spring template response into DTOs instead use JSONNode class of Jackson databind API.

JsonNode root = objectMapper.readTree(response.getBody());

You can find more information at
https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/JsonNode.html

You can traverse down the tree and could retrieve the value of the attribute directly without any DTOs.


问:
Is this possible to make navbar attach to top?
enter image description here

I want to make my navbar attach to  the top  how is this possible?

答:
Use CSS property position:fixed on your navbar in the CSS.
And you are good to go.


问:
Direct Line App Extension - How and where are messages cached?
I have a few questions about the new Direct Line App Extension for App Services on Azure announced at Build 2020.
The "normal" direct line services cached messages at their own regional servers. Now that this extension allows the App Service of a bot to act as the Direct Line endpoint, is the conversation with it's messages cached in the app service? And does this mean, one could for example edit the settings of the conversation caching like cache duration etc.?

And I guess the pricing of messages via the Direct Line App Extension is still via the premium channel pricing category?

I tried to find information about it in the botframework repositories and in the documentation, but it seems like there is no additional information about it available yet.

Thank you for your help.

答:
Direct Line Application Service Extension does not cache messages at all. This is by design as caching would require access to your app service storage, which means you would need storage, or access to an outside service. However, adding a caching service defeats the purpose of the VNET scenario DL ASE was primarily built to serve.

Regarding pricing, the Bot Service tiers are the same in both a Direct Line bot and one that utilizes DL ASE. So, on the face of it, they appear the same.


问:
Centering rotated text in
How to vertically center "There is information text" here?

Better - without changing html.

Also why doesn't max-width: 15px!important limit the width of the first  (tall) to 15px? How to limit it without changing the general width parameter?

td {width: 60px}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="1">
    <tbody>
        <tr>
            <td style="max-width: 15px!important;" rowspan="12">
                <p style="transform: rotate(270deg); white-space: nowrap">There is information text</p>
            </td>
            <td>1</td>
        </tr>
        <tr>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
        </tr>
        <tr>
            <td>4</td>
        </tr>
        <tr>
            <td>5</td>
        </tr>
        <tr>
            <td>6</td>
        </tr>
        <tr>
            <td>7</td>
        </tr>
        <tr>
            <td>8</td>
        </tr>
        <tr>
            <td>9</td>
        </tr>
        <tr>
            <td>10</td>
        </tr>
        <tr>
            <td>11</td>
        </tr>
        <tr>
            <td>12</td>
        </tr>
    </tbody>
</table></code>```

It is need to center it so without rotation to make it work with:

Is it possible? It is the most interesting for me.

答:
I think this may solve your question with the use of rotation

td { width:60px}
p{
 margin: 0;
    position: absolute;
    top: 50%;
    -moz-transform: translateX(-50%) translateY(-50%) rotate(-90deg);
    -webkit-transform: translateX(-50%) translateY(-50%) rotate(-90deg);
    transform: translateX(-50%) translateY(-50%) rotate(270deg);
    left: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="1">
    <tbody>
        <tr>
            <td style="max-width: 15px!important;position:relative;" rowspan="12">
                <p style="white-space: nowrap">There is information text</p>
            </td>
            <td>1</td>
        </tr>
        <tr>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
        </tr>
        <tr>
            <td>4</td>
        </tr>
        <tr>
            <td>5</td>
        </tr>
        <tr>
            <td>6</td>
        </tr>
        <tr>
            <td>7</td>
        </tr>
        <tr>
            <td>8</td>
        </tr>
        <tr>
            <td>9</td>
        </tr>
        <tr>
            <td>10</td>
        </tr>
        <tr>
            <td>11</td>
        </tr>
        <tr>
            <td>12</td>
        </tr>
    </tbody>
</table></code>```

Title: Centering rotated text in <td>

Body:
How to vertically center "There is information text" here?

Better - without changing html.

Also why doesn't max-width: 15px!important limit the width of the first  (tall) to 15px? How to limit it without changing the general width parameter?

td {width: 60px}

There is information text

            1

            2

            3

            4

            5

            6

            7

            8

            9

            10

            11

            12

It is need to center it so without rotation to make it work with:

Is it possible? It is the most interesting for me.

Body:
I think this may solve your question with the use of rotation

td { width:60px}
p{
 margin: 0;
    position: absolute;
    top: 50%;
    -moz-transform: translateX(-50%) translateY(-50%) rotate(-90deg);
    -webkit-transform: translateX(-50%) translateY(-50%) rotate(-90deg);
    transform: translateX(-50%) translateY(-50%) rotate(270deg);
    left: 50%;
}

<table border="1">
    <tbody>
        <tr>
            <td style="max-width: 15px!important;position:relative;" rowspan="12">
                <p style="white-space: nowrap">There is information text</p>
            </td>
            <td>1</td>
        </tr>
        <tr>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
        </tr>
        <tr>
            <td>4</td>
        </tr>
        <tr>
            <td>5</td>
        </tr>
        <tr>
            <td>6</td>
        </tr>
        <tr>
            <td>7</td>
        </tr>
        <tr>
            <td>8</td>
        </tr>
        <tr>
            <td>9</td>
        </tr>
        <tr>
            <td>10</td>
        </tr>
        <tr>
            <td>11</td>
        </tr>
        <tr>
            <td>12</td>
        </tr>
    </tbody>
</table>


问:
Error in constexpr using clang to compile TensorFlow
I am trying to compile tensorflow using clang ,
And getting following error regarding constexpr

```<code>In file included from /tensorflow/tensorflow/lite/tools/make/downloads/absl/absl/time/clock.h:26:
/tensorflow/tensorflow/lite/tools/make/downloads/absl/absl/time/time.h:1404:55: error: constexpr function's 2nd parameter type 'std::ratio<60>' is not a literal type
constexpr Duration FromInt64(int64_t v, std::ratio<60>) {
                                        ~~~~~~~~~~~~~~^
/toolkit/include/usr/h/public/ratio:100:9: note: 'ratio<60, 1>' is not literal because it is not an aggregate and has no constexpr constructors other than copy or move constructors
        struct ratio
               ^
</code>```

This is the relevant piece of code:

template <std::intmax_t N>
constexpr Duration FromInt64(int64_t v, std::ratio<1, N>) {
  static_assert(0 < N && N <= 1000 * 1000 * 1000, "Unsupported ratio");
  // Subsecond ratios cannot overflow.
  return MakeNormalizedDuration(
      v / N, v % N * kTicksPerNanosecond * 1000 * 1000 * 1000 / N);
}

constexpr Duration FromInt64(int64_t v, std::ratio<60>) {
  return (v <= (std::numeric_limits<int64_t>::max)() / 60 &&
          v >= (std::numeric_limits<int64_t>::min)() / 60)
             ? MakeDuration(v * 60)
             : v > 0 ? InfiniteDuration() : -InfiniteDuration();
}
```

Thanks if someone can point me to the right direction

答:
Chances are that std::ratio is not yet defined in that context. If std::ratio is incomplete, the code will not compile. Perhaps try to

```<code>#include <ratio>
</code>```

before compiling that code.

Body:
I am trying to compile tensorflow using clang ,
And getting following error regarding constexpr

In file included from /tensorflow/tensorflow/lite/tools/make/downloads/absl/absl/time/clock.h:26:
/tensorflow/tensorflow/lite/tools/make/downloads/absl/absl/time/time.h:1404:55: error: constexpr function's 2nd parameter type 'std::ratio<60>' is not a literal type
constexpr Duration FromInt64(int64_t v, std::ratio<60>) {
                                        ~~~~~~~~~~~~~~^
/toolkit/include/usr/h/public/ratio:100:9: note: 'ratio<60, 1>' is not literal because it is not an aggregate and has no constexpr constructors other than copy or move constructors
        struct ratio
               ^

This is the relevant piece of code:

template <std::intmax_t N>
constexpr Duration FromInt64(int64_t v, std::ratio<1, N>) {
  static_assert(0 < N && N <= 1000 * 1000 * 1000, "Unsupported ratio");
  // Subsecond ratios cannot overflow.
  return MakeNormalizedDuration(
      v / N, v % N * kTicksPerNanosecond * 1000 * 1000 * 1000 / N);
}

constexpr Duration FromInt64(int64_t v, std::ratio<60>) {
  return (v <= (std::numeric_limits<int64_t>::max)() / 60 &&
          v >= (std::numeric_limits<int64_t>::min)() / 60)
             ? MakeDuration(v * 60)
             : v > 0 ? InfiniteDuration() : -InfiniteDuration();
}

Thanks if someone can point me to the right direction

Body:
Chances are that std::ratio is not yet defined in that context. If std::ratio is incomplete, the code will not compile. Perhaps try to

#include <ratio>

before compiling that code.


问:
Selecting a random string from a list results in column being populated with NULLS [SQL]
I am trying to populate a column in sql by replacing old values with new values from a list.

```<code>SELECT CHOOSE(ROUND(RAND() * 3, 1) + 1,'Bill','Steve','Jack')
</code>```

Running this query gives me instances of NULLS which i don't want, why am i getting NULLS?

答:
CHOOSE is just shorthand for a CASE expression. I talk about how an expression like RAND() can be evaluated more than once here (see the section "Expressions can be evaluated more than once"). I also talk about this here (search the page for "RAND()").

Basically, what happens is CHOOSE(expr, a, b) gets expanded to:

```<code>CASE
  WHEN expr = 1 THEN a
  WHEN expr = 2 THEN b
  ELSE NULL
END
</code>```

Each time you see expr there, it can be evaluated again. So the first time you call RAND() it could yield 2, then it moves to the next WHEN, and this time it could yield 1, then all that's left is NULL.

The solution is to generate RAND() just once, e.g.

```<code>DECLARE @rand tinyint = CONVERT(tinyint, (RAND()*3) + 1);

SELECT CHOOSE(@rand,'Bill','Steve','Jack');
</code>```

Body:
I am trying to populate a column in sql by replacing old values with new values from a list.

SELECT CHOOSE(ROUND(RAND() * 3, 1) + 1,'Bill','Steve','Jack')

Running this query gives me instances of NULLS which i don't want, why am i getting NULLS?

Body:
CHOOSE is just shorthand for a CASE expression. I talk about how an expression like RAND() can be evaluated more than once here (see the section "Expressions can be evaluated more than once"). I also talk about this here (search the page for "RAND()").

Basically, what happens is CHOOSE(expr, a, b) gets expanded to:

CASE
  WHEN expr = 1 THEN a
  WHEN expr = 2 THEN b
  ELSE NULL
END

Each time you see expr there, it can be evaluated again. So the first time you call RAND() it could yield 2, then it moves to the next WHEN, and this time it could yield 1, then all that's left is NULL.

The solution is to generate RAND() just once, e.g.

DECLARE @rand tinyint = CONVERT(tinyint, (RAND()*3) + 1);

SELECT CHOOSE(@rand,'Bill','Steve','Jack');


问:
Play video on the img click
I´m trying to play my local video on the image click, but somehow, the video does not play. It shows the video "box", but the video wont play. Any ideas how to make the video play after clicking the image?

Thanks a lot!
HTML part: Suppose there is video in each img div - for this example, I included only 1 video

```<code><div class="container-gallery" id="portfolio">
        <h1>Portfolio gallery</h1>
        <div class="wrapper-gallery" id="index-gallery">
            <div class="gallery-img img1">
                <div><a href="#">First image</a></div>
                <video class="hidden" width="1000" controls>
                    <source src="../video/#6.mp4" type="video/mp4">
                 </video>
            </div>
            <div class="gallery-img img2">
                <div><a href="#">Second image</a></div>
            </div>
            <div class="gallery-img img3">
                <div><a href="#">Third image</a></div>
            </div>
            <div class="gallery-img img4">
                <div><a href="#">Fourth image</a></div>
            </div>
            <div class="gallery-img img5">
                <div><a href="#">Fifth image</a></div>
            </div>
            <div class="gallery-img img6">
                <div><a href="#">Sixth image</a></div>
            </div>
            <div class="gallery-img img7">
                <div><a href="#">Seventh image</a></div>
            </div>
        </div>
    </div>
</code>```

CSS Part:

```<code>.img-window {
    width: 90vw;
    height: 92vh;
    background-color: rgba(0,0,0,.8);
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;
}

.img-window img {
   max-height: 80vh;
   max-width: 80vw;
   z-index: 1000;
}

.hidden {
    display: none;
}

.show {
    display: block;
}
</code>```

Javascript Part

```<code>let galleryImages = document.querySelectorAll('.gallery-img');
let video = document.querySelector('video');
let getLatestOpenedImg;

if(galleryImages) {
    galleryImages.forEach(function(image, index) {
        image.onclick = function(e) {
            e.preventDefault();

            getLatestOpenedImg = index + 1;
            let container = document.body;
            let newVidWindow = document.createElement("div");
            container.appendChild(newVidWindow);
            newVidWindow.setAttribute("class", "img-window");
            newVidWindow.setAttribute("onclick", "closeImg()");

            newVidWindow.appendChild(video);
            video.classList.remove('hidden');
            video.classList.add('show');
            video.play();
        }
    });
}

function closeImg() {
    document.querySelector(".img-window").remove();
}
</code>```

答:
Here's your code unchanged, it seems to be working fine.

Could it be a browser issue that's preventing embedded videos from playing?

let galleryImages = document.querySelectorAll('.gallery-img');
let video = document.querySelector('video');
let getLatestOpenedImg;

if(galleryImages) {
    galleryImages.forEach(function(image, index) {
        image.onclick = function(e) {
            e.preventDefault();

            getLatestOpenedImg = index + 1;
            let container = document.body;
            let newVidWindow = document.createElement("div");
            container.appendChild(newVidWindow);
            newVidWindow.setAttribute("class", "img-window");
            newVidWindow.setAttribute("onclick", "closeImg()");

            newVidWindow.appendChild(video);
            video.classList.remove('hidden');
            // not needed
            //video.classList.add('show');
            video.play();
        }
    });
}

function closeImg() {
    document.querySelector(".img-window").remove();
} ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.img-window {
    width: 90vw;
    height: 92vh;
    background-color: rgba(0,0,0,.8);
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;
}

.img-window img {
   max-height: 80vh;
   max-width: 80vw;
   z-index: 1000;
}

.hidden {
    display: none;
}

/* not needed
.show {
    display: block;
}
*/</code>```

Portfolio gallery

First image

      <video class="hidden" width="1000" controls>
        <source
          src="https://interactive-examples.mdn.mozilla.net/media/examples/flower.mp4"
          type="video/mp4">
      </video>

Second image

Third image

Fourth image

Fifth image

Sixth image

Seventh image

```

Title: Play video on the img click

Body:
I´m trying to play my local video on the image click, but somehow, the video does not play. It shows the video "box", but the video wont play. Any ideas how to make the video play after clicking the image?

Thanks a lot!
HTML part: Suppose there is video in each img div - for this example, I included only 1 video

Portfolio gallery

First image

                <video class="hidden" width="1000" controls>
                    <source src="../video/#6.mp4" type="video/mp4">
                 </video>

Second image

Third image

Fourth image

Fifth image

Sixth image

Seventh image

CSS Part:

.img-window {
    width: 90vw;
    height: 92vh;
    background-color: rgba(0,0,0,.8);
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;
}

.img-window img {
   max-height: 80vh;
   max-width: 80vw;
   z-index: 1000;
}

.hidden {
    display: none;
}

.show {
    display: block;
}

Javascript Part

let galleryImages = document.querySelectorAll('.gallery-img');
let video = document.querySelector('video');
let getLatestOpenedImg;

if(galleryImages) {
    galleryImages.forEach(function(image, index) {
        image.onclick = function(e) {
            e.preventDefault();

            getLatestOpenedImg = index + 1;
            let container = document.body;
            let newVidWindow = document.createElement("div");
            container.appendChild(newVidWindow);
            newVidWindow.setAttribute("class", "img-window");
            newVidWindow.setAttribute("onclick", "closeImg()");

            newVidWindow.appendChild(video);
            video.classList.remove('hidden');
            video.classList.add('show');
            video.play();
        }
    });
}

function closeImg() {
    document.querySelector(".img-window").remove();
}

Body:
Here's your code unchanged, it seems to be working fine.

Could it be a browser issue that's preventing embedded videos from playing?

let galleryImages = document.querySelectorAll('.gallery-img');
let video = document.querySelector('video');
let getLatestOpenedImg;

if(galleryImages) {
    galleryImages.forEach(function(image, index) {
        image.onclick = function(e) {
            e.preventDefault();

            getLatestOpenedImg = index + 1;
            let container = document.body;
            let newVidWindow = document.createElement("div");
            container.appendChild(newVidWindow);
            newVidWindow.setAttribute("class", "img-window");
            newVidWindow.setAttribute("onclick", "closeImg()");

            newVidWindow.appendChild(video);
            video.classList.remove('hidden');
            // not needed
            //video.classList.add('show');
            video.play();
        }
    });
}

function closeImg() {
    document.querySelector(".img-window").remove();
}

.img-window {
    width: 90vw;
    height: 92vh;
    background-color: rgba(0,0,0,.8);
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;
}

.img-window img {
   max-height: 80vh;
   max-width: 80vw;
   z-index: 1000;
}

.hidden {
    display: none;
}

/* not needed
.show {
    display: block;
}
*/

<div class="container-gallery" id="portfolio">
  <h1>Portfolio gallery</h1>
  <div class="wrapper-gallery" id="index-gallery">
    <div class="gallery-img img1">
      <div><a href="#">First image</a></div>
      <video class="hidden" width="1000" controls>
        <source
          src="https://interactive-examples.mdn.mozilla.net/media/examples/flower.mp4"
          type="video/mp4">
      </video>
    </div>
    <div class="gallery-img img2">
      <div><a href="#">Second image</a></div>
    </div>
    <div class="gallery-img img3">
      <div><a href="#">Third image</a></div>
    </div>
    <div class="gallery-img img4">
      <div><a href="#">Fourth image</a></div>
    </div>
    <div class="gallery-img img5">
      <div><a href="#">Fifth image</a></div>
    </div>
    <div class="gallery-img img6">
      <div><a href="#">Sixth image</a></div>
    </div>
    <div class="gallery-img img7">
      <div><a href="#">Seventh image</a></div>
    </div>
  </div>
</div>


问:
Is it possible to pass data between custom service worker and React components?
I have a create-react-app and I created a custom service worker in public folder. In the src I have the default serviceWorker.js file. In the public folder in the custom service worker file I added a push event listener like this:

```<code> self.addEventListener("push", function (event) {

  const someData= event.data.text();
  const title = "Test";
  const options = {
    body: someData,
    icon: "./someIcon.png",
    badge: "./someIcon.png",
  };
    event.waitUntil(self.registration.showNotification(title, options));
});
</code>```

The thing is that before I show this notification I need to apply some transformation to the data I receive from the event and for that I need this data in some react component, do the transformation there and then do this: event.waitUntil(self.registration.showNotification(title, options));
with the transformation applied to my data so the user gets that data as notification eventually. Is it possible to achieve something like this?

答:
It's not really possible to accomplish that, because you don't have any way of knowing whether there will be a web page open for your origin when the push event handler is invoked. Your service worker might be woken up at any point in time with a push event received from your push notification server, and there's no guarantee that your web app will also be open.

Because of this, I'd try not to go down the road of implementing something that used postMessage() to conditionally talk between the service worker and the client page (if it is open), since that's code that would only work some of the time.

Instead, you should implement all the code that you need in order to display the notification inside of the service worker itself.

Body:
I have a create-react-app and I created a custom service worker in public folder. In the src I have the default serviceWorker.js file. In the public folder in the custom service worker file I added a push event listener like this:

 self.addEventListener("push", function (event) {

  const someData= event.data.text();
  const title = "Test";
  const options = {
    body: someData,
    icon: "./someIcon.png",
    badge: "./someIcon.png",
  };
    event.waitUntil(self.registration.showNotification(title, options));
});

The thing is that before I show this notification I need to apply some transformation to the data I receive from the event and for that I need this data in some react component, do the transformation there and then do this: event.waitUntil(self.registration.showNotification(title, options));
with the transformation applied to my data so the user gets that data as notification eventually. Is it possible to achieve something like this?