问:
Excel Array Formula showing same results
I'm having issues with my array formula showing the same result on all cells. I know it's a simple Index Match, but can someone help me with whats missing to have it return multiple unique values? Most examples I've found only help with returning results within a range, but this is specific to matching text.
=INDEX(Info2020[[Modêle]:[Catégorie]],MATCH(Criteria,Info2020[Catégorie],0),1) (obviously Ctl+Shft+Enter to get {})

Ideal output:

答:
would want all "modele" codes that match the "categorie" to be displayed.

That does not seem to be what is being shown by your Ideal Output table.  And I really don't see how your Ideal Output is derived from the data you've posted.

But to do what you write, you can use a formula like the one below.

You need to convert all of the rows that match your criteria (the categorie) and then INDEX into the appropriate column.  The AGGREGATE function allows you to extract the matching rows in order.

Suggest you break apart the formula, and/or use the formula evaluation tool, to better understand how it is working.

```<code>=IFERROR(INDEX(Table1[[Modêle]:[Modêle]],AGGREGATE(15,6,1/(Table1[[Catégorie]:[Catégorie]]=J$2)*ROW(Table1[[Modêle]:[Modêle]]),ROWS($1:1))-ROW(Table1[#Headers])),"")
</code>```

and fill down until you get blanks.

Data

Output

Body:
would want all "modele" codes that match the "categorie" to be displayed.

That does not seem to be what is being shown by your Ideal Output table.  And I really don't see how your Ideal Output is derived from the data you've posted.

But to do what you write, you can use a formula like the one below.

You need to convert all of the rows that match your criteria (the categorie) and then INDEX into the appropriate column.  The AGGREGATE function allows you to extract the matching rows in order.

Suggest you break apart the formula, and/or use the formula evaluation tool, to better understand how it is working.

=IFERROR(INDEX(Table1[[Modêle]:[Modêle]],AGGREGATE(15,6,1/(Table1[[Catégorie]:[Catégorie]]=J$2)*ROW(Table1[[Modêle]:[Modêle]]),ROWS($1:1))-ROW(Table1[#Headers])),"")

and fill down until you get blanks.

Data

Output


来源: stackexchange

问:
How to write re_path url in django for reading special character?
I am working with Django URL pattern for my project. I am sending a String containing special characters and numbers. While reading a string in python function it won't get the ? in a function.

html

```<code>{% for user_name in userSet%}
<a class="dropdown-item" href="/slackNotification/{{user_name}}/{{data.question}}">{{ user_name }}</a>
{% endfor %}
</code>```

url

```<code>path('slackNotification/<str:slack_user_name>/<str:question>',views.slackNotification)
</code>```

When I get the all details through URL then string whichever I received in the python code it won't contain ? mark even though my input contains Special characters and numbers.

input: What is your name?
output: What is your name(question mark not available;)

Question
I have tried this:

```<code>re_path(r'^slackNotification/<str:slack_user_name>/(?P<question>\w+)',views.slackNotification)
</code>```

Output
The current path didn't match any of the url

I want to know the exact regular expression for my requirement ??

答:
Your first path() is correct as long as each path component in your URL is URL-encoded. ? is a special character in URLs: It denotes the end of the path and anything coming after it is interpreted as query parameters:

```<code>http://www.example.com/apples?color=green
</code>```

has the path http://www.example.com/apples and a query parameter color with value green.

Therefore, if you want to the string "What is your name?" to be included in your path, you need to make sure it's URL-encoded: What%20is%20your%20name%3F where %3F is the URL-encoded ? and %20 is for <space>.

ContentLicense: CC BY-SA 4.0

Body:
I am working with Django URL pattern for my project. I am sending a String containing special characters and numbers. While reading a string in python function it won't get the ? in a function.

html

{% for user_name in userSet%}
{{ user_name }}
{% endfor %}

url

path('slackNotification/<str:slack_user_name>/<str:question>',views.slackNotification)

When I get the all details through URL then string whichever I received in the python code it won't contain ? mark even though my input contains Special characters and numbers.

input: What is your name?
output: What is your name(question mark not available;)

Question
I have tried this:

re_path(r'^slackNotification/<str:slack_user_name>/(?P<question>\w+)',views.slackNotification)

Output
The current path didn't match any of the url

I want to know the exact regular expression for my requirement ??

Body:
Your first path() is correct as long as each path component in your URL is URL-encoded. ? is a special character in URLs: It denotes the end of the path and anything coming after it is interpreted as query parameters:

http://www.example.com/apples?color=green

has the path http://www.example.com/apples and a query parameter color with value green.

Therefore, if you want to the string "What is your name?" to be included in your path, you need to make sure it's URL-encoded: What%20is%20your%20name%3F where %3F is the URL-encoded ? and %20 is for <space>.


问:
storing input from text box tkinter
```<code>import tkinter

window = tkinter.Tk()
window.configure(background="grey90")
window.title("Downloader")
window.geometry("300x300")
window.resizable(False, False)

entry = tkinter.Entry(window)
entry.place(x=70,y=68)
entry.configure(highlightbackground="grey90")

button = tkinter.Button(window, text="Download",
command=window.destroy, highlightbackground="grey90")
button.place(x=110,y=120)
to_download = entry.get()
window.mainloop()
print(to_download)
</code>```

Hello, I need some help in storing the output after the "download" button is clicked,what I want is when "download" button is clicked the value to be stored to_download (if an input is placed not None) and the window to close.

Right now the window is closing but it doesn't store the value

答:
Hi you should set a function to command and do this in function

```<code>import tkinter

def press():
    global to_download
    if to_download:
        print(to_download)
        window.destroy()

window = tkinter.Tk()
window.configure(background="grey90")
window.title("Downloader")
window.geometry("300x300")
window.resizable(False, False)

entry = tkinter.Entry(window)
entry.place(x=70,y=68)
entry.configure(highlightbackground="grey90")

button = tkinter.Button(window, text="Download",
command=press, highlightbackground="grey90")
button.place(x=110,y=120)
window.mainloop()
</code>```

Title: storing input from text box tkinter

Body:
import tkinter

window = tkinter.Tk()
window.configure(background="grey90")
window.title("Downloader")
window.geometry("300x300")
window.resizable(False, False)

entry = tkinter.Entry(window)
entry.place(x=70,y=68)
entry.configure(highlightbackground="grey90")

button = tkinter.Button(window, text="Download",
command=window.destroy, highlightbackground="grey90")
button.place(x=110,y=120)
to_download = entry.get()
window.mainloop()
print(to_download)

Hello, I need some help in storing the output after the "download" button is clicked,what I want is when "download" button is clicked the value to be stored to_download (if an input is placed not None) and the window to close.

Right now the window is closing but it doesn't store the value

Body:
Hi you should set a function to command and do this in function

import tkinter

def press():
    global to_download
    if to_download:
        print(to_download)
        window.destroy()

window = tkinter.Tk()
window.configure(background="grey90")
window.title("Downloader")
window.geometry("300x300")
window.resizable(False, False)

entry = tkinter.Entry(window)
entry.place(x=70,y=68)
entry.configure(highlightbackground="grey90")

button = tkinter.Button(window, text="Download",
command=press, highlightbackground="grey90")
button.place(x=110,y=120)
window.mainloop()


问:
CoreLocationManager never pauses?
Trying to get my app to use less power, it's tracking location always in the background but I'd like for it automatically pause so I can turn on region watching and use that to resume precise location monitoring once the user moves around a bit.

I've had the app on for half an hour now and the location service is not pausing.  I think this has been the case since Apple changed location stuff in iOS 13? I'm not really sure.  All the documentation I can find online seems extremely outdated.

Any advice is greatly appreciated, relevant code follows:

```<code>init() {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = 10
        locationManager.activityType = .fitness
        locationManager.requestAlwaysAuthorization()
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.pausesLocationUpdatesAutomatically = true
        locationManager.showsBackgroundLocationIndicator = true
        locationManager.startUpdatingLocation()
    }
    func locationManagerDidPauseLocationUpdates(_ manager: CLLocationManager) {
        delegate?.paused(tracker: self)
        print("MT | LOCATION SERVICES PAUSED!") <---- NEVER GETTING CALLED (been running for 40 minutes now, no location updates, still going though?)
        // if not already, start region monitoring

    }
 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // Collect data
        for location in locations {
           print("MT | New Location: \(location)")
        }
    }
</code>```

答:
Do you think maybe your activityType is preventing the location services to pause?

activityType

The location manager uses the information in this property as a cue to determine when location updates may be automatically paused. Pausing updates gives the system the opportunity to save power in situations where the user's location is not likely to be changing.

.fitness

This activity might cause location updates to be paused only when the user does not move a significant distance over a period of time.

I don't know what your particular use case is but, have you considered using the following function for background location tracking?

startMonitoringSignificantLocationChanges()

You may also try a mix of both, turning on significant location changes for day to day use and allowsBackgroundLocation when doing something like tracking a run, etc.

Title: CoreLocationManager never pauses?

Body:
Trying to get my app to use less power, it's tracking location always in the background but I'd like for it automatically pause so I can turn on region watching and use that to resume precise location monitoring once the user moves around a bit.

I've had the app on for half an hour now and the location service is not pausing.  I think this has been the case since Apple changed location stuff in iOS 13? I'm not really sure.  All the documentation I can find online seems extremely outdated.

Any advice is greatly appreciated, relevant code follows:

init() {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = 10
        locationManager.activityType = .fitness
        locationManager.requestAlwaysAuthorization()
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.pausesLocationUpdatesAutomatically = true
        locationManager.showsBackgroundLocationIndicator = true
        locationManager.startUpdatingLocation()
    }
    func locationManagerDidPauseLocationUpdates(_ manager: CLLocationManager) {
        delegate?.paused(tracker: self)
        print("MT | LOCATION SERVICES PAUSED!") <---- NEVER GETTING CALLED (been running for 40 minutes now, no location updates, still going though?)
        // if not already, start region monitoring

    }
 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // Collect data
        for location in locations {
           print("MT | New Location: \(location)")
        }
    }


问:
Authentication & Roles with Guards/Decorators: How to pass user object?
With the help of Guards/Decorators I try to check a JWT first and then the roles a user has.

I have read the documentation regarding Authentication, Guards and Decorators and understand the principles behind them.

However, what I cannot do is to somehow make the authenticated user from JWT-Guard available to Roles-Guards.

In every example that I found, exactly this part that is interesting for me is skipped / left out...

Grateful for every tip!

This is my latest try:

jwt.strategy.ts

```<code>import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { JwtPayload } from './jwt.model';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      passReqToCallback: true,
      ignoreExpiration: false,
      secretOrKey: '0000',
      expiresIn: '3 days'
    });
  }

  async validate(payload: JwtPayload) {
    return {
      id: payload.id,
      email: payload.email,
      username: payload.username
    };
  }
}
</code>```

roles.guard.ts

```<code>import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {
  }

  canActivate(context: ExecutionContext): boolean {
    const roles = this.reflector.get<string[]>('roles', context.getHandler());

    if (!roles) {
      return false;
    }

    const request = context.switchToHttp().getRequest();
    const user = request.user ??? // THIS is what is missing

    return roles.some((role) => {
      return role === user.role;
    });
  }
}
</code>```

roles.decorator.ts

```<code>import { SetMetadata } from '@nestjs/common';

export const Roles = (...roles: string[]) => SetMetadata('roles', roles);
</code>```

users.controller.ts

```<code>@UseGuards(AuthGuard('jwt'))
@Roles('admin', 'member')
@Get('/')
async doSomething(@Req() req): Promise<User> {
  return await this.usersService.doSomething(req.user.id);
}
</code>```

答:
Your decorator and guards look fine, but from the snippet of your users.controller.ts file it is not clear whether the roles guard is actually applied for the GET / route.

I do, however, have an NestJS app with a quite similar setup based on the guards documentation. The following code in users.controller.ts works as intended:

@UseGuards(JwtAuthGuard, RolesGuard)
@Controller('/users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get()
  @Roles(UserRole.ADMIN)
  public async index(): Promise<User[]> {
    return this.userService.findAll();
  }

  // ...
}
```

Note how both the auth and roles guard are activated in the same scope and that JwtAuthGuard is added before RolesGuard. If I were to change the sequence of the guards then the RolesGuard would not be able to retrieve the user of the request.

Also, you might want to have a look at a similar question from some time ago which contains some details on the order of guards in different scopes.

Body:
With the help of Guards/Decorators I try to check a JWT first and then the roles a user has.

I have read the documentation regarding Authentication, Guards and Decorators and understand the principles behind them.

However, what I cannot do is to somehow make the authenticated user from JWT-Guard available to Roles-Guards.

In every example that I found, exactly this part that is interesting for me is skipped / left out...

Grateful for every tip!

This is my latest try:

jwt.strategy.ts

import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { JwtPayload } from './jwt.model';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      passReqToCallback: true,
      ignoreExpiration: false,
      secretOrKey: '0000',
      expiresIn: '3 days'
    });
  }

  async validate(payload: JwtPayload) {
    return {
      id: payload.id,
      email: payload.email,
      username: payload.username
    };
  }
}

roles.guard.ts

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {
  }

  canActivate(context: ExecutionContext): boolean {
    const roles = this.reflector.get<string[]>('roles', context.getHandler());

    if (!roles) {
      return false;
    }

    const request = context.switchToHttp().getRequest();
    const user = request.user ??? // THIS is what is missing

    return roles.some((role) => {
      return role === user.role;
    });
  }
}

roles.decorator.ts

import { SetMetadata } from '@nestjs/common';

export const Roles = (...roles: string[]) => SetMetadata('roles', roles);

users.controller.ts

@UseGuards(AuthGuard('jwt'))
@Roles('admin', 'member')
@Get('/')
async doSomething(@Req() req): Promise<User> {
  return await this.usersService.doSomething(req.user.id);
}

Body:
Your decorator and guards look fine, but from the snippet of your users.controller.ts file it is not clear whether the roles guard is actually applied for the GET / route.

I do, however, have an NestJS app with a quite similar setup based on the guards documentation. The following code in users.controller.ts works as intended:

@UseGuards(JwtAuthGuard, RolesGuard)
@Controller('/users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get()
  @Roles(UserRole.ADMIN)
  public async index(): Promise<User[]> {
    return this.userService.findAll();
  }

  // ...
}

Note how both the auth and roles guard are activated in the same scope and that JwtAuthGuard is added before RolesGuard. If I were to change the sequence of the guards then the RolesGuard would not be able to retrieve the user of the request.

Also, you might want to have a look at a similar question from some time ago which contains some details on the order of guards in different scopes.


问:
using word "not" as a name of c++ class causes error on VS2019
I'm migrating existing project to VS2019. Having very simple structure that successfully compiled in all previous versions:

```<code>template <class Marker>
struct not
{
    // ...
</code>```

error C2332: 'struct': missing tag name

NOTE-1 I've checked by pre-compilatinion generation that not is not substituted with some macros, output of *.i file fully matches declaration above

NOTE-2 of course if I rename not->inv then all everything is right

答:
not is a keyword in standard C++ which can be used as alternative for the ! token.

MSVC does not support the alternative operator tokens by default. Therefore they are available as identifiers and you don't get an error on your declaration.

But in compliance mode with the /permissive- compiler flag, these tokens are considered keywords with their standard meaning and so they are not available as identifiers.

I suggest not using not as identifier, even when not using compliance mode, because that makes your code non-standard and non-portable.

see https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance

and Why does VS not define the alternative tokens for logical operators?

Body:
I'm migrating existing project to VS2019. Having very simple structure that successfully compiled in all previous versions:

template <class Marker>
struct not
{
    // ...

error C2332: 'struct': missing tag name

NOTE-1 I've checked by pre-compilatinion generation that not is not substituted with some macros, output of *.i file fully matches declaration above

NOTE-2 of course if I rename not->inv then all everything is right


问:
Setup nginx with react and express
I have a nginx server currently up and running, however I can only acces my website and not mywebsite/contact for exemple.

I have a react build as frontend @ : /usr/share/nginx/site/front
And a express server running with pm2 @ port 5000. in /usr/share/nginx/site/express

I would like all requests to /api go to the express server running on port 5000.
The rest should go to my react front end, Normally the react build will automatically proxy all /api/ requests to the port 5000 express server, this works locally.

How would I have to change the default nginx config @ sites-available/

I currently have :

```<code>server{
  listen 80 default_server;
  listen [::]:80 default_server
  root /usr/share/nginx/site/front

  index index.html
}
</code>```

答:
Try this</p>

```<code>    server {
    listen      80  default_server;
    listen      [::]:80 default_server;
    server_name _;

    location /api/ {    # Backend
        proxy_pass  http://127.0.0.1:500;

        access_log  /var/log/nginx/back.out.log;
        error_log   /var/log/nginx/back.err.log;
    }

    location / {    # Frontend
        root        /usr/share/nginx/site/front;
        index       index.html;
        try_files   $uri $uri/ /index.html;

        access_log  /var/log/nginx/front.out.log;
        error_log   /var/log/nginx/front.err.log;
    }
}
</code>```

Title: Setup nginx with react and express

Body:
I have a nginx server currently up and running, however I can only acces my website and not mywebsite/contact for exemple.

I have a react build as frontend @ : /usr/share/nginx/site/front
And a express server running with pm2 @ port 5000. in /usr/share/nginx/site/express

I would like all requests to /api go to the express server running on port 5000.
The rest should go to my react front end, Normally the react build will automatically proxy all /api/ requests to the port 5000 express server, this works locally.

How would I have to change the default nginx config @ sites-available/

I currently have :

server{
  listen 80 default_server;
  listen [::]:80 default_server
  root /usr/share/nginx/site/front

  index index.html
}

Body:
Try this

    server {
    listen      80  default_server;
    listen      [::]:80 default_server;
    server_name _;

    location /api/ {    # Backend
        proxy_pass  http://127.0.0.1:500;

        access_log  /var/log/nginx/back.out.log;
        error_log   /var/log/nginx/back.err.log;
    }

    location / {    # Frontend
        root        /usr/share/nginx/site/front;
        index       index.html;
        try_files   $uri $uri/ /index.html;

        access_log  /var/log/nginx/front.out.log;
        error_log   /var/log/nginx/front.err.log;
    }
}


问:
Getting a sum into a Table from another table based on a field value
And I'm looking at whether it's possible to have a table which is used to record a daily output? The daily output would be recorded under an ID (as there are several IDs).

Therefore, I have two tables, one is the list of IDs which have the field for IDs & total output, and another table that records the daily output which contains the fields for IDs, Daily Output, & Output Date.

Therefore I want to put the sum of recorded Daily Output by respective ID into the ID List table.

答:
To create this answer, I used the following structure:

```<code>tblDailyOutput - table name
   (Key field is combination of ID and Output_Date)
ID - number field
Output_Date - date field
Daily_Output - number field holding the daily totals

tblOutputTotal - table name
ID - number field, key field
TotalOutput - number field
</code>```

I would do this in two steps:

Delete the records in Output_Total. By deleting the records you do not have to add new IDs and update existing IDs, but all of the IDs will be there every time.

Query:

```<code>DELETE tblOutputTotal.* FROM tblOutputTotal;
</code>```

Create an append query to Output_Total that adds the totals to your Output_Total table.

Query:

```<code>INSERT INTO tblOutputTotal ( ID, TotalOutput )
    SELECT tblDailyOutput.ID, Sum(tblDailyOutput.Daily_Output) AS SumOfDaily_Output
    FROM tblDailyOutput
    GROUP BY tblDailyOutput.ID;
</code>```

Body:
To create this answer, I used the following structure:

tblDailyOutput - table name
   (Key field is combination of ID and Output_Date)
ID - number field
Output_Date - date field
Daily_Output - number field holding the daily totals

tblOutputTotal - table name
ID - number field, key field
TotalOutput - number field

I would do this in two steps:

Delete the records in Output_Total. By deleting the records you do not have to add new IDs and update existing IDs, but all of the IDs will be there every time.

Query:

DELETE tblOutputTotal.* FROM tblOutputTotal;

Create an append query to Output_Total that adds the totals to your Output_Total table.

Query:

INSERT INTO tblOutputTotal ( ID, TotalOutput )
    SELECT tblDailyOutput.ID, Sum(tblDailyOutput.Daily_Output) AS SumOfDaily_Output
    FROM tblDailyOutput
    GROUP BY tblDailyOutput.ID;


问:
JavaScript map object not saving object keys?
So I'm trying to add an entry to a map object with the key being an object but it doesn't seem to work.

```<code>let myMap = new Map();
myMap.set({type : 'sum', val : 10},1);
console.log(myMap.get({type:'sum',val:10})); <---- this returns undefined
</code>```

why is it returning undefined instead of 1?

答:
It should accept key value pair only, so your are providing object in place of key.

```<code> myMap.set({type : 'sum', val : 10},1);
 myMap.set( {key:1, val: {type : 'sum', val : 10}} );
</code>```

Try using a key and adding the object { type:'',val:''} to it as its value. Try wrapping '1' into the object itself

As you will need a key to access it.

Ref: [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map][1]

It will return myMap.size

Body:
So I'm trying to add an entry to a map object with the key being an object but it doesn't seem to work.

let myMap = new Map();
myMap.set({type : 'sum', val : 10},1);
console.log(myMap.get({type:'sum',val:10})); <---- this returns undefined

why is it returning undefined instead of 1?

Body:
It should accept key value pair only, so your are providing object in place of key.

 myMap.set({type : 'sum', val : 10},1);
 myMap.set( {key:1, val: {type : 'sum', val : 10}} );

Try using a key and adding the object { type:'',val:''} to it as its value. Try wrapping '1' into the object itself

As you will need a key to access it.

Ref: [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map][1]

It will return myMap.size


问:
Javascript to remove an object from an array if one element in the object contains a string
I have an array of objects such as:

```<code>{
    "value": [
        {
            "attachment_text": "Support: hello there! I need some help syncing records",
            "ticket_text": "Ticket 1537 from ronburgundy@news.com"
        },
        {
            "attachment_text": "Copied from original request - 401 unathorized",
            "ticket_text": "Ticket 1459 from klaus.kinsky@kinsky.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1173 from sophia@copolla.com"
        },
        {
            "attachment_text": "Hello, we need to troubleshoot some problems",
            "ticket_text": "Ticket 1591 from pat@pending.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1483 from bugs@bunny.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1393 from elmer@fudd.com"
        }
    ]
}
</code>```

What javascript can I use to remove any objects where the attachment_text field contains the string "Contact request"?

Preferably pure javascript (i.e. not a library such as lodash)

答:
You can use the filter method of Array Objects in JavaScript. I have created a demo for you below:

var data = {
  "value": [{
      "attachment_text": "Support: hello there! I need some help syncing records",
      "ticket_text": "Ticket 1537 from ronburgundy@news.com"
    },
    {
      "attachment_text": "Copied from original request - 401 unathorized",
      "ticket_text": "Ticket 1459 from klaus.kinsky@kinsky.com"
    },
    {
      "attachment_text": "Contact request form received",
      "ticket_text": "Ticket 1173 from sophia@copolla.com"
    },
    {
      "attachment_text": "Hello, we need to troubleshoot some problems",
      "ticket_text": "Ticket 1591 from pat@pending.com"
    },
    {
      "attachment_text": "Contact request form received",
      "ticket_text": "Ticket 1483 from bugs@bunny.com"
    },
    {
      "attachment_text": "Contact request form received",
      "ticket_text": "Ticket 1393 from elmer@fudd.com"
    }
  ]
}

const result = data.value.filter((data) => !data["attachment_text"].includes("Contact request"))
console.log(result)```

Body:
I have an array of objects such as:

{
    "value": [
        {
            "attachment_text": "Support: hello there! I need some help syncing records",
            "ticket_text": "Ticket 1537 from ronburgundy@news.com"
        },
        {
            "attachment_text": "Copied from original request - 401 unathorized",
            "ticket_text": "Ticket 1459 from klaus.kinsky@kinsky.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1173 from sophia@copolla.com"
        },
        {
            "attachment_text": "Hello, we need to troubleshoot some problems",
            "ticket_text": "Ticket 1591 from pat@pending.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1483 from bugs@bunny.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1393 from elmer@fudd.com"
        }
    ]
}

What javascript can I use to remove any objects where the attachment_text field contains the string "Contact request"?

Preferably pure javascript (i.e. not a library such as lodash)


问:
Can't figure out why my ActivityTransition example doesn't work with BroadcastReceiver
I have looked at multiple examples and implementations, I have no more ideas to check. I hope for outside perspective to see if I have missed something. Here is complete project on github for full source

It doesn't give me any errors or anything, it even shows that I have registered my request successfully. But I don't get any result in my BroadcastReceiver.

Manifest:

```<code><uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver
        android:exported="true"
        android:enabled="true"
        android:name="com.example.myapplication.ActivityTransitionBroadcastReceiver"
        android:permission="com.google.android.gms.permission.ACTIVITY_RECOGNITION">
        <intent-filter>
            <action android:name="com.example.myapplication.ACTION_PROCESS_ACTIVITY_TRANSITIONS"/>
        </intent-filter>
    </receiver>

</application>
</code>```

Main Activity:

```<code>    List<ActivityTransition> transitions = new ArrayList<>();

    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.STILL)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                    .build());
    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.STILL)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                    .build());
    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.IN_VEHICLE)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                    .build());
    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.IN_VEHICLE)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                    .build());

    ActivityTransitionRequest request = new ActivityTransitionRequest(transitions);

    Intent intent = new Intent(this.getApplicationContext(), ActivityTransitionBroadcastReceiver.class);
    intent.setAction(ActivityTransitionBroadcastReceiver.INTENT_ACTION);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    Task<Void> task = ActivityRecognition.getClient(this.getApplicationContext())
            .requestActivityTransitionUpdates(request, pendingIntent);
    task.addOnSuccessListener(aVoid -> Log.i(TAG, "\n\nTransitions API was successfully registered.\n\n"))
            .addOnFailureListener(e -> Log.e(TAG, "Transitions API could not be registered: " + e));
</code>```

答:
First of all if you using compileSdkVersion 29 you need to request permission "Manifest.permission.ACTIVITY_RECOGNITION", so your MainActivity wiil be like this:

```<code>package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.location.ActivityRecognition;
import com.google.android.gms.location.ActivityTransition;
import com.google.android.gms.location.ActivityTransitionRequest;
import com.google.android.gms.location.DetectedActivity;
import com.google.android.gms.tasks.Task;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "TransitionTest";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onResume(){
        super.onResume();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            checkIfAlreadyHavePermission();
        }else{
            requestForUpdates();
        }
    }

    private void checkIfAlreadyHavePermission() {
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION);
        if (result == PackageManager.PERMISSION_GRANTED) {
            requestForUpdates();
        } else {
            requestPermissions();
        }
    }

    private void requestPermissions(){
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.ACTIVITY_RECOGNITION},
                1);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                requestForUpdates();
            } else {
                Toast.makeText(MainActivity.this, "Recognition permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void requestForUpdates(){
        List<ActivityTransition> transitions = new ArrayList<>();

        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.STILL)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.STILL)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.IN_VEHICLE)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.IN_VEHICLE)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.WALKING)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.ON_FOOT)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                        .build());

        ActivityTransitionRequest request = new ActivityTransitionRequest(transitions);

        Intent intent = new Intent(getApplicationContext(), ActivityTransitionBroadcastReceiver.class);
        intent.setAction(ActivityTransitionBroadcastReceiver.INTENT_ACTION);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        Task<Void> task = ActivityRecognition.getClient(getApplicationContext())
                .requestActivityTransitionUpdates(request, pendingIntent);
        task.addOnSuccessListener(aVoid -> Log.i(TAG, "\n\nTransitions API was successfully registered.\n\n"))
                .addOnFailureListener(e -> Log.e(TAG, "Transitions API could not be registered: " + e));
    }

}
</code>```

in Manifest also try to add

```<code><uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

<receiver
    android:name="com.example.myapplication.ActivityBroadcastReceiver"
    android:permission="com.google.android.gms.permission.ACTIVITY_RECOGNITION">
    <intent-filter>
        <action android:name="com.example.myapplication.ACTION_PROCESS_ACTIVITY_TRANSITIONS"/>
    </intent-filter>
</receiver>
</code>```

And for convenience create NotificationHelper class:

```<code>class NotificationHelper {

    static void sendNotification(Context context, String textContent) {

        Intent notificationIntent;
        PendingIntent pendingIntent;

        notificationIntent = new Intent(context, MainActivity.class);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
        pendingIntent = PendingIntent.getActivity(context, new Random().nextInt(100) + 1,
                notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context,"notif_ch_myapplication")
                .setContentTitle(context.getResources().getString(R.string.app_name))
                .setContentText(textContent)
                .setChannelId("notif_ch_myapplication")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                .setContentIntent(pendingIntent);

        if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            mBuilder.setSmallIcon(R.mipmap.ic_launcher);
            mBuilder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher_background));
        } else {
            mBuilder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher_background));
            mBuilder.setSmallIcon(R.mipmap.ic_launcher);
        }

        android.app.NotificationManager notificationManager = (android.app.NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            NotificationChannel channel = new NotificationChannel("notif_ch_myapplication",
                    context.getResources().getString(R.string.app_name),
                    android.app.NotificationManager.IMPORTANCE_DEFAULT);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
        if (notificationManager != null) {
            notificationManager.notify(new Random().nextInt(100) + 1, mBuilder.build());
        }
    }
}
</code>```

and use it in ActivityTransitionBroadcastReceiver:

```<code>    public  class ActivityTransitionBroadcastReceiver extends BroadcastReceiver {

    public static final String INTENT_ACTION = "com.example.myapplication.ACTION_PROCESS_ACTIVITY_TRANSITIONS";

    @Override
    public  void onReceive(Context context, Intent intent) {
        if (ActivityTransitionResult.hasResult(intent)) {
            ActivityTransitionResult result = ActivityTransitionResult.extractResult(intent);
            for (ActivityTransitionEvent event : Objects.requireNonNull(result).getTransitionEvents()) {
                NotificationHelper.sendNotification(context, "Activity type:" + event.getActivityType()
                        + " Transition type: " + event.getTransitionType());
            }
        }
    }
}
</code>```

In such way you will be able to check in without android studio.

And one more important thing: when you will install application - go outside for at least 10 minutes or you can shake the phone at least a minute. In my case I have received new activity transition event only in ~5-7 minutes.

Body:
I have looked at multiple examples and implementations, I have no more ideas to check. I hope for outside perspective to see if I have missed something. Here is complete project on github for full source

It doesn't give me any errors or anything, it even shows that I have registered my request successfully. But I don't get any result in my BroadcastReceiver.

Manifest:

<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver
        android:exported="true"
        android:enabled="true"
        android:name="com.example.myapplication.ActivityTransitionBroadcastReceiver"
        android:permission="com.google.android.gms.permission.ACTIVITY_RECOGNITION">
        <intent-filter>
            <action android:name="com.example.myapplication.ACTION_PROCESS_ACTIVITY_TRANSITIONS"/>
        </intent-filter>
    </receiver>

</application>

Main Activity:

    List<ActivityTransition> transitions = new ArrayList<>();

    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.STILL)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                    .build());
    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.STILL)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                    .build());
    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.IN_VEHICLE)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                    .build());
    transitions.add(
            new ActivityTransition.Builder()
                    .setActivityType(DetectedActivity.IN_VEHICLE)
                    .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                    .build());

    ActivityTransitionRequest request = new ActivityTransitionRequest(transitions);

    Intent intent = new Intent(this.getApplicationContext(), ActivityTransitionBroadcastReceiver.class);
    intent.setAction(ActivityTransitionBroadcastReceiver.INTENT_ACTION);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    Task<Void> task = ActivityRecognition.getClient(this.getApplicationContext())
            .requestActivityTransitionUpdates(request, pendingIntent);
    task.addOnSuccessListener(aVoid -> Log.i(TAG, "\n\nTransitions API was successfully registered.\n\n"))
            .addOnFailureListener(e -> Log.e(TAG, "Transitions API could not be registered: " + e));

Body:
First of all if you using compileSdkVersion 29 you need to request permission "Manifest.permission.ACTIVITY_RECOGNITION", so your MainActivity wiil be like this:

package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.location.ActivityRecognition;
import com.google.android.gms.location.ActivityTransition;
import com.google.android.gms.location.ActivityTransitionRequest;
import com.google.android.gms.location.DetectedActivity;
import com.google.android.gms.tasks.Task;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "TransitionTest";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onResume(){
        super.onResume();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            checkIfAlreadyHavePermission();
        }else{
            requestForUpdates();
        }
    }

    private void checkIfAlreadyHavePermission() {
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION);
        if (result == PackageManager.PERMISSION_GRANTED) {
            requestForUpdates();
        } else {
            requestPermissions();
        }
    }

    private void requestPermissions(){
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.ACTIVITY_RECOGNITION},
                1);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                requestForUpdates();
            } else {
                Toast.makeText(MainActivity.this, "Recognition permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void requestForUpdates(){
        List<ActivityTransition> transitions = new ArrayList<>();

        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.STILL)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.STILL)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.IN_VEHICLE)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.IN_VEHICLE)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.WALKING)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                        .build());
        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.ON_FOOT)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                        .build());

        ActivityTransitionRequest request = new ActivityTransitionRequest(transitions);

        Intent intent = new Intent(getApplicationContext(), ActivityTransitionBroadcastReceiver.class);
        intent.setAction(ActivityTransitionBroadcastReceiver.INTENT_ACTION);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        Task<Void> task = ActivityRecognition.getClient(getApplicationContext())
                .requestActivityTransitionUpdates(request, pendingIntent);
        task.addOnSuccessListener(aVoid -> Log.i(TAG, "\n\nTransitions API was successfully registered.\n\n"))
                .addOnFailureListener(e -> Log.e(TAG, "Transitions API could not be registered: " + e));
    }

}

in Manifest also try to add

<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

<receiver
    android:name="com.example.myapplication.ActivityBroadcastReceiver"
    android:permission="com.google.android.gms.permission.ACTIVITY_RECOGNITION">
    <intent-filter>
        <action android:name="com.example.myapplication.ACTION_PROCESS_ACTIVITY_TRANSITIONS"/>
    </intent-filter>
</receiver>

And for convenience create NotificationHelper class:

class NotificationHelper {

    static void sendNotification(Context context, String textContent) {

        Intent notificationIntent;
        PendingIntent pendingIntent;

        notificationIntent = new Intent(context, MainActivity.class);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
        pendingIntent = PendingIntent.getActivity(context, new Random().nextInt(100) + 1,
                notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context,"notif_ch_myapplication")
                .setContentTitle(context.getResources().getString(R.string.app_name))
                .setContentText(textContent)
                .setChannelId("notif_ch_myapplication")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                .setContentIntent(pendingIntent);

        if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            mBuilder.setSmallIcon(R.mipmap.ic_launcher);
            mBuilder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher_background));
        } else {
            mBuilder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher_background));
            mBuilder.setSmallIcon(R.mipmap.ic_launcher);
        }

        android.app.NotificationManager notificationManager = (android.app.NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            NotificationChannel channel = new NotificationChannel("notif_ch_myapplication",
                    context.getResources().getString(R.string.app_name),
                    android.app.NotificationManager.IMPORTANCE_DEFAULT);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
        if (notificationManager != null) {
            notificationManager.notify(new Random().nextInt(100) + 1, mBuilder.build());
        }
    }
}

and use it in ActivityTransitionBroadcastReceiver:

    public  class ActivityTransitionBroadcastReceiver extends BroadcastReceiver {

    public static final String INTENT_ACTION = "com.example.myapplication.ACTION_PROCESS_ACTIVITY_TRANSITIONS";

    @Override
    public  void onReceive(Context context, Intent intent) {
        if (ActivityTransitionResult.hasResult(intent)) {
            ActivityTransitionResult result = ActivityTransitionResult.extractResult(intent);
            for (ActivityTransitionEvent event : Objects.requireNonNull(result).getTransitionEvents()) {
                NotificationHelper.sendNotification(context, "Activity type:" + event.getActivityType()
                        + " Transition type: " + event.getTransitionType());
            }
        }
    }
}

In such way you will be able to check in without android studio.

And one more important thing: when you will install application - go outside for at least 10 minutes or you can shake the phone at least a minute. In my case I have received new activity transition event only in ~5-7 minutes.


问:
How to use existing scale set as cluster node in Azure Service Fabric cluster
I am trying to deploy Service Fabric cluster through ARM template and attach the existing scale set. The pipeline is getting executed properly with no error but when i open service fabric in portal the status is "waiting for nodes". I don't know where i am making mistake. I am using the same certificate thumbprint which is there in scale set. my certificate is stored in KeyVault. Here is my ARM template

```<code>{
    "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "clusterName": {
            "type": "string",
            "defaultValue": "GEN-UNIQUE",
            "metadata": {
                "description": "Name of your cluster - Between 3 and 23 characters. Letters and numbers only"
            }
        },
        "clusterLocation": {
            "type": "string",
            "defaultValue": "westus",
            "metadata": {
                "description": "Location of the Cluster"
            }
        },
        "applicationStartPort": {
            "type": "int",
            "defaultValue": 20000
        },
        "applicationEndPort": {
            "type": "int",
            "defaultValue": 30000
        },
        "ephemeralStartPort": {
            "type": "int",
            "defaultValue": 49152
        },
        "ephemeralEndPort": {
            "type": "int",
            "defaultValue": 65534
        },
        "fabricTcpGatewayPort": {
            "type": "int",
            "defaultValue": 19000
        },
        "fabricHttpGatewayPort": {
            "type": "int",
            "defaultValue": 19080
        },
        "clusterProtectionLevel": {
            "type": "string",
            "allowedValues": [
                "None",
                "Sign",
                "EncryptAndSign"
            ],
            "defaultValue": "EncryptAndSign",
            "metadata": {
                "description": "Protection level.Three values are allowed - EncryptAndSign, Sign, None. It is best to keep the default of EncryptAndSign, unless you have a need not to"
            }
        },
        "certificateThumbprint": {
            "type": "string",
            "defaultValue": "GEN-CUSTOM-DOMAIN-SSLCERT-THUMBPRINT",
            "metadata": {
                "description": "Certificate Thumbprint"
            }
        },
        "certificateStoreValue": {
            "defaultValue": "My",
            "allowedValues": [
                "My"
            ],
            "type": "string",
            "metadata": {
                "description": "The store name where the cert will be deployed in the virtual machine"
            }
        },
        "supportLogStorageAccountName": {
            "type": "string",
            "defaultValue": "[toLower( concat('sflogs', uniqueString(resourceGroup().id),'2'))]",
            "metadata": {
                "description": "Name for the storage account that contains support logs from the cluster"
            }
        },
        "blobEndpoint":{
            "type": "string"
        },
        "queueEndpoint":{
            "type": "string"
        },
        "tableEndpoint":{
            "type": "string"
        },
        "InstanceCount": {
            "type": "int",
            "defaultValue": 5,
            "metadata": {
                "description": "Instance count for node type"
            }
        },
        "vmNodeTypeName": {
            "type": "string"
        },
        "nodeTypes":{
            "type": "array"
        },
        "lbIPName": {
            "type": "string"
        },
        "fqdn":{
            "type": "string"
        },
        "reliabilityLevel":{
            "type": "string"
        },
        "upgradeMode":{
            "type": "string"
        }
    },
    "variables":{
        "storageApiVersion": "2016-01-01",
        "publicIPApiVersion": "2015-06-15"
        },
"resources": [
   {
    "apiVersion": "2018-02-01",
    "type": "Microsoft.ServiceFabric/clusters",
    "name": "[parameters('clusterName')]",
    "location": "[parameters('clusterLocation')]",
    "dependsOn": [],
    "properties": {
        "addonFeatures": [
            "DnsService"
        ],
        "certificate": {
            "thumbprint": "[parameters('certificateThumbprint')]",
            "x509StoreName": "[parameters('certificateStoreValue')]"
        },
        "clientCertificateCommonNames": [],
        "clientCertificateThumbprints": [],
        "clusterState": "Default",
        "diagnosticsStorageAccountConfig": {
            "storageAccountName": "[parameters('supportLogStorageAccountName')]",
            "protectedAccountKeyName": "StorageAccountKey1",
            "blobEndpoint": "[parameters('blobEndpoint')]",
            "queueEndpoint": "[parameters('queueEndpoint')]",
            "tableEndpoint": "[parameters('tableEndpoint')]"
        },
        "fabricSettings": [
            {
                "parameters": [
                    {
                        "name": "ClusterProtectionLevel",
                        "value": "[parameters('clusterProtectionLevel')]"
                    }
                ],
                "name": "Security"
            }
        ],
        "managementEndpoint": "[concat('https://',parameters('fqdn'),':',parameters('fabricHttpGatewayPort'))]",
        "nodeTypes": "[parameters('nodeTypes')]",
        "reliabilityLevel": "[parameters('reliabilityLevel')]",
        "upgradeMode": "[parameters('upgradeMode')]"
    }
   }
 ]

}
</code>```

答:
For this deployment error, you can look through these problems and solutions in this blog.
It might be caused by the Certificate Thumbprint Issue and KeyVault issue.

If it's no luck, try to change the VM sizes or change the region of the nodes or just rebuild like this.

For more reference about SFC deployment with key vault cert, you also could refer to this article.

Body:
I am trying to deploy Service Fabric cluster through ARM template and attach the existing scale set. The pipeline is getting executed properly with no error but when i open service fabric in portal the status is "waiting for nodes". I don't know where i am making mistake. I am using the same certificate thumbprint which is there in scale set. my certificate is stored in KeyVault. Here is my ARM template

{
    "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "clusterName": {
            "type": "string",
            "defaultValue": "GEN-UNIQUE",
            "metadata": {
                "description": "Name of your cluster - Between 3 and 23 characters. Letters and numbers only"
            }
        },
        "clusterLocation": {
            "type": "string",
            "defaultValue": "westus",
            "metadata": {
                "description": "Location of the Cluster"
            }
        },
        "applicationStartPort": {
            "type": "int",
            "defaultValue": 20000
        },
        "applicationEndPort": {
            "type": "int",
            "defaultValue": 30000
        },
        "ephemeralStartPort": {
            "type": "int",
            "defaultValue": 49152
        },
        "ephemeralEndPort": {
            "type": "int",
            "defaultValue": 65534
        },
        "fabricTcpGatewayPort": {
            "type": "int",
            "defaultValue": 19000
        },
        "fabricHttpGatewayPort": {
            "type": "int",
            "defaultValue": 19080
        },
        "clusterProtectionLevel": {
            "type": "string",
            "allowedValues": [
                "None",
                "Sign",
                "EncryptAndSign"
            ],
            "defaultValue": "EncryptAndSign",
            "metadata": {
                "description": "Protection level.Three values are allowed - EncryptAndSign, Sign, None. It is best to keep the default of EncryptAndSign, unless you have a need not to"
            }
        },
        "certificateThumbprint": {
            "type": "string",
            "defaultValue": "GEN-CUSTOM-DOMAIN-SSLCERT-THUMBPRINT",
            "metadata": {
                "description": "Certificate Thumbprint"
            }
        },
        "certificateStoreValue": {
            "defaultValue": "My",
            "allowedValues": [
                "My"
            ],
            "type": "string",
            "metadata": {
                "description": "The store name where the cert will be deployed in the virtual machine"
            }
        },
        "supportLogStorageAccountName": {
            "type": "string",
            "defaultValue": "[toLower( concat('sflogs', uniqueString(resourceGroup().id),'2'))]",
            "metadata": {
                "description": "Name for the storage account that contains support logs from the cluster"
            }
        },
        "blobEndpoint":{
            "type": "string"
        },
        "queueEndpoint":{
            "type": "string"
        },
        "tableEndpoint":{
            "type": "string"
        },
        "InstanceCount": {
            "type": "int",
            "defaultValue": 5,
            "metadata": {
                "description": "Instance count for node type"
            }
        },
        "vmNodeTypeName": {
            "type": "string"
        },
        "nodeTypes":{
            "type": "array"
        },
        "lbIPName": {
            "type": "string"
        },
        "fqdn":{
            "type": "string"
        },
        "reliabilityLevel":{
            "type": "string"
        },
        "upgradeMode":{
            "type": "string"
        }
    },
    "variables":{
        "storageApiVersion": "2016-01-01",
        "publicIPApiVersion": "2015-06-15"
        },
"resources": [
   {
    "apiVersion": "2018-02-01",
    "type": "Microsoft.ServiceFabric/clusters",
    "name": "[parameters('clusterName')]",
    "location": "[parameters('clusterLocation')]",
    "dependsOn": [],
    "properties": {
        "addonFeatures": [
            "DnsService"
        ],
        "certificate": {
            "thumbprint": "[parameters('certificateThumbprint')]",
            "x509StoreName": "[parameters('certificateStoreValue')]"
        },
        "clientCertificateCommonNames": [],
        "clientCertificateThumbprints": [],
        "clusterState": "Default",
        "diagnosticsStorageAccountConfig": {
            "storageAccountName": "[parameters('supportLogStorageAccountName')]",
            "protectedAccountKeyName": "StorageAccountKey1",
            "blobEndpoint": "[parameters('blobEndpoint')]",
            "queueEndpoint": "[parameters('queueEndpoint')]",
            "tableEndpoint": "[parameters('tableEndpoint')]"
        },
        "fabricSettings": [
            {
                "parameters": [
                    {
                        "name": "ClusterProtectionLevel",
                        "value": "[parameters('clusterProtectionLevel')]"
                    }
                ],
                "name": "Security"
            }
        ],
        "managementEndpoint": "[concat('https://',parameters('fqdn'),':',parameters('fabricHttpGatewayPort'))]",
        "nodeTypes": "[parameters('nodeTypes')]",
        "reliabilityLevel": "[parameters('reliabilityLevel')]",
        "upgradeMode": "[parameters('upgradeMode')]"
    }
   }
 ]

}


问:
ReactJS: How to fetch data from API on button click
I am making an app to fetch data from a recipeDB API, and right now I need to click on the search button have it console.log some data. Right now it is giving me a network error when attempting to fetch the resource. I have my code setup like this</p>

```<code>import React, { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const API_ID = "0fc98505";
  const API_KEY = "5e81ce76845f459b53f9fbe775e81e53";

  const [recipes, setRecipes] = useState([]);

  const getRecipes = async () => {
    const response = await fetch(
      `https://api.edamam.com/search?q=chicken&app_id=${API_ID}&app_key=${API_KEY}`
    );
    const data = await response.json();
    setRecipes(data)
    console.log(data);

  };

  return (
    <div className="App">
      <button onClick={getRecipes}>Retrive data</button>
    </div>
  );
}
</code>```

答:
If there is a network error, this means that your request is executed. I think the error here lies in your APP_ID and API_KEY. Another reason might be CORS. For more details visit MDN page.
Also you can check out «Network» tab in your developer tools(F12) where error description is sometimes shown in response body.</p>

Body:
I am making an app to fetch data from a recipeDB API, and right now I need to click on the search button have it console.log some data. Right now it is giving me a network error when attempting to fetch the resource. I have my code setup like this

import React, { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const API_ID = "0fc98505";
  const API_KEY = "5e81ce76845f459b53f9fbe775e81e53";

  const [recipes, setRecipes] = useState([]);

  const getRecipes = async () => {
    const response = await fetch(
      `https://api.edamam.com/search?q=chicken&app_id=${API_ID}&app_key=${API_KEY}`
    );
    const data = await response.json();
    setRecipes(data)
    console.log(data);

  };

  return (

      <button onClick={getRecipes}>Retrive data</button>

  );
}


问:
How to get parts of a string via regular expressions in Kotlin or Java?
Suppose you have a string http://server.com/s123456 and want to get 123456 from it. Or http://server.com/s123456&a=100 and get 123456, 100. Many different situations where you want to have parts of a string.

In order to match strings I use regular expressions.

```<code>@Test
fun test() {
    val text = "http://server.com/s123456" // Source string.
    val reg = "^http://server.com/s\\d+\$".toRegex()
    assertEquals(true, reg.matches(text))

    // Try to split the string with findAll().
    val a: Sequence<MatchResult> = reg.findAll(text, 0)
    val names = a.map { it.groupValues[0] }.joinToString()
    println(names) // http://server.com/s123456
}
</code>```

But it doesn't split the source string into chars and digits, just prints: http://server.com/s123456. Is there a way to write a mask, so that we can retrieve numbers (or any other parts) from the string?

答: You need to use capture group around the the part that you interested. Use this "^http://server.com/s(\\d+)\$" and use it.groupValues[1].

Body:
Suppose you have a string http://server.com/s123456 and want to get 123456 from it. Or http://server.com/s123456&a=100 and get 123456, 100. Many different situations where you want to have parts of a string.

In order to match strings I use regular expressions.

@Test
fun test() {
    val text = "http://server.com/s123456" // Source string.
    val reg = "^http://server.com/s\\d+\$".toRegex()
    assertEquals(true, reg.matches(text))

    // Try to split the string with findAll().
    val a: Sequence<MatchResult> = reg.findAll(text, 0)
    val names = a.map { it.groupValues[0] }.joinToString()
    println(names) // http://server.com/s123456
}

But it doesn't split the source string into chars and digits, just prints: http://server.com/s123456. Is there a way to write a mask, so that we can retrieve numbers (or any other parts) from the string?


问:
Request with Symfony HttpClient returns code 0, when the same request with postman works fine
I have a weird problem where a request I make (to my mercure hub) with postman works fine, however the Publisher class (from the Symfony mercure bundle), which uses the Symfony HttpClient will yield in a response code 0.
According to my research that means that the URL can't be found, or no Response was returned?

I first thought it might have to do something with the Publisher class itself, which is why opened this Issue on Github, but after some playing around I thought that maybe there is a communication error with my containers? I tried giving my mercure container "networks: internal", which some other containers use aswell, but that didn't help either.

Any ideas are greatly appreciated..

/e: my docker-compose:

```<code>version: "3"

services:
  traefik:
    image: traefik:v1.7
    ports:
      - 80:80
      - 443:443
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - ./.docker/traefik/traefik.toml:/etc/traefik/traefik.toml
    networks:
      - proxy
    labels:
      - traefik.enable=true
      - traefik.docker.network=proxy
      - traefik.frontend.rule=Host:traefik.heracles.local
      - traefik.port=8080

  nginx:
    image: nginx:1.17-alpine
    volumes:
      - ./Source:/var/www
      - ./.docker/nginx/conf/nginx.conf:/etc/nginx/nginx.conf
    links:
      - php
    networks:
      - internal
      - proxy
    labels:
      - traefik.docker.network=proxy
      - traefik.enable=true
      - traefik.basic.frontend.rule=Host:heracles.local
      - traefik.basic.port=80

  php:
    build:
      args:
        USER_ID: ${USER_ID}
      context: ./.docker/php
    volumes:
      - ./Source:/var/www
      - ./.docker/php/conf/cli.ini:/etc/php/7.4/cli/conf.d/zz-symfony.ini
      - ./.docker/php/conf/fpm.ini:/etc/php/7.4/fpm/conf.d/zz-symfony.ini
      - ./.docker/php/conf/xdebug.ini:/etc/php/7.4/fpm/conf.d/zz-xdebug.ini
      - ./.docker/php/conf/opcache.ini:/etc/php/7.4/fpm/conf.d/zz-opcache.ini
      - ./.docker/php/conf/pool.conf:/etc/php/7.4/fpm/pool.d/www.conf
    networks:
      - internal
    labels:
      - traefik.enable=false

  db:
    image: mysql:5.7
    env_file:
      - .env
    volumes:
      - db_data:/var/lib/mysql
      - ./.docker/mysql/conf.d:/etc/mysql/conf.d
    command:
      - --character-set-server=utf8mb4
      - --collation-server=utf8mb4_unicode_ci
      - --skip-character-set-client-handshake
    networks:
      - internal
    labels:
      - traefik.enable=false
    restart: always

  adminer:
    image: adminer
    networks:
      - internal
      - proxy
    labels:
      - traefik.docker.network=proxy
      - traefik.enable=true
      - traefik.basic.frontend.rule=Host:db.heracles.local
      - traefik.basic.port=8080

  blackfire:
    image: blackfire/blackfire
    networks:
      - internal
    labels:
      - traefik.enable=false

  mailhog:
    image: mailhog/mailhog
    networks:
      - internal
      - proxy
    labels:
      - traefik.docker.network=proxy
      - traefik.enable=true
      - traefik.basic.frontend.rule=Host:mail.heracles.local
      - traefik.basic.port=8025

  mercure:
    image: dunglas/mercure
    environment:
      - ALLOW_ANONYMOUS=1
      - CORS_ALLOWED_ORIGINS=*
      - JWT_KEY=ASD
      - PUBLISH_ALLOWED_ORIGINS=http://heracles.local
      - ADDR=:3000
    ports:
      - 3000:3000

networks:
  internal:
  proxy:
    external: true

volumes:
  db_data:
</code>```

答:
In reference to your comment, your MERCURE_PUBLISH_URL .env variable must indeed refer to your Mercure container, but there's no need for the port indication. If the name of your Mercure container is "mercure", the environment variable should be set like so :

MERCURE_PUBLISH_URL=http://mercure/.well-known/mercure

(Replace http by https if your connection is secured)

Body:
I have a weird problem where a request I make (to my mercure hub) with postman works fine, however the Publisher class (from the Symfony mercure bundle), which uses the Symfony HttpClient will yield in a response code 0.
According to my research that means that the URL can't be found, or no Response was returned?

I first thought it might have to do something with the Publisher class itself, which is why opened this Issue on Github, but after some playing around I thought that maybe there is a communication error with my containers? I tried giving my mercure container "networks: internal", which some other containers use aswell, but that didn't help either.

Any ideas are greatly appreciated..

/e: my docker-compose:

version: "3"

services:
  traefik:
    image: traefik:v1.7
    ports:
      - 80:80
      - 443:443
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - ./.docker/traefik/traefik.toml:/etc/traefik/traefik.toml
    networks:
      - proxy
    labels:
      - traefik.enable=true
      - traefik.docker.network=proxy
      - traefik.frontend.rule=Host:traefik.heracles.local
      - traefik.port=8080

  nginx:
    image: nginx:1.17-alpine
    volumes:
      - ./Source:/var/www
      - ./.docker/nginx/conf/nginx.conf:/etc/nginx/nginx.conf
    links:
      - php
    networks:
      - internal
      - proxy
    labels:
      - traefik.docker.network=proxy
      - traefik.enable=true
      - traefik.basic.frontend.rule=Host:heracles.local
      - traefik.basic.port=80

  php:
    build:
      args:
        USER_ID: ${USER_ID}
      context: ./.docker/php
    volumes:
      - ./Source:/var/www
      - ./.docker/php/conf/cli.ini:/etc/php/7.4/cli/conf.d/zz-symfony.ini
      - ./.docker/php/conf/fpm.ini:/etc/php/7.4/fpm/conf.d/zz-symfony.ini
      - ./.docker/php/conf/xdebug.ini:/etc/php/7.4/fpm/conf.d/zz-xdebug.ini
      - ./.docker/php/conf/opcache.ini:/etc/php/7.4/fpm/conf.d/zz-opcache.ini
      - ./.docker/php/conf/pool.conf:/etc/php/7.4/fpm/pool.d/www.conf
    networks:
      - internal
    labels:
      - traefik.enable=false

  db:
    image: mysql:5.7
    env_file:
      - .env
    volumes:
      - db_data:/var/lib/mysql
      - ./.docker/mysql/conf.d:/etc/mysql/conf.d
    command:
      - --character-set-server=utf8mb4
      - --collation-server=utf8mb4_unicode_ci
      - --skip-character-set-client-handshake
    networks:
      - internal
    labels:
      - traefik.enable=false
    restart: always

  adminer:
    image: adminer
    networks:
      - internal
      - proxy
    labels:
      - traefik.docker.network=proxy
      - traefik.enable=true
      - traefik.basic.frontend.rule=Host:db.heracles.local
      - traefik.basic.port=8080

  blackfire:
    image: blackfire/blackfire
    networks:
      - internal
    labels:
      - traefik.enable=false

  mailhog:
    image: mailhog/mailhog
    networks:
      - internal
      - proxy
    labels:
      - traefik.docker.network=proxy
      - traefik.enable=true
      - traefik.basic.frontend.rule=Host:mail.heracles.local
      - traefik.basic.port=8025

  mercure:
    image: dunglas/mercure
    environment:
      - ALLOW_ANONYMOUS=1
      - CORS_ALLOWED_ORIGINS=*
      - JWT_KEY=ASD
      - PUBLISH_ALLOWED_ORIGINS=http://heracles.local
      - ADDR=:3000
    ports:
      - 3000:3000

networks:
  internal:
  proxy:
    external: true

volumes:
  db_data:


问:
Transpose column names to rows and put values in seperate column
I have the following table which you can also find in the SQL fiddle here:

```<code>CREATE TABLE Flows (
    Product TEXT,
    Inbound_Date DATE,
    Outbound_Date DATE,
    Return_Date DATE,
    Quantity VARCHAR(255)
);

INSERT INTO Flows
(Product, Inbound_Date, Outbound_Date, Return_Date, Quantity)
VALUES

("Product A", "2019-01-01", NULL, NULL, "400"),
("Product A", NULL, "2019-05-08", NULL, "200"),
("Product A", NULL, NULL, "2019-06-25", "600"),

("Product B", "2019-03-08", NULL, NULL, "380"),
("Product B", NULL, "2019-03-15", NULL, "120"),
("Product B", NULL, NULL, "2019-04-17", "610");
</code>```

I use the following SQL to get the values from the table:

```<code>SELECT Product, Inbound_Date, Outbound_Date, Return_Date, sum(Quantity)
FROM Flows
GROUP BY 1,2,3,4;
</code>```

All this works fine so far.

However, now I want to achieve that the dates are displayed in one column called FLow_Date.

The result should look like this:

```<code>Product          Date_Type            Flow_Date
Product A        Inbound_Date        2019-01-01
Product A        Oubound_Date        2019-05-08
Product A        Return_Date         2019-06-25
Product B        Inbound_Date        2019-03-08
Product B        Outbound_Date       2019-03-15
Product B        Return_Date         2019-04-17
</code>```

What do I need to change in my code to make it work?

答:
I think you just need case expressions:

```<code>select f.product,
       (case when inbound_date is not null then 'inbound_date'
             when outbound_date is not null then 'outbound_date'
             when return_date is not null then 'return_date'
        end) date_type,
       (case when inbound_date is not null then inbound_date
             when outbound_date is not null then outbound_date
             when return_date is not null then return_date
        end) as flow_date
from flows f;
</code>```

This becomes more complicated if you can have multiple non-NULL values per row.

In that case, union all is a simple enough approach

```<code>select fd.*
from ((select f.product, 'inbound_date' as date_type, inbound_date as flow_date
       from flows f
      ) union all
      (select f.product, 'outbound_date' as date_type, outbound_date as flow_date
       from flows f
      ) union all
      (select f.product, 'return_date' as date_type, return_date as flow_date
       from flows f
      )
     ) fd
where flow_date is not null;
</code>```

This is not necessarily the most efficient method (in this case), but it works well.  If flows is really a view, then alternatives might be preferred.

Body:
I have the following table which you can also find in the SQL fiddle here:

CREATE TABLE Flows (
    Product TEXT,
    Inbound_Date DATE,
    Outbound_Date DATE,
    Return_Date DATE,
    Quantity VARCHAR(255)
);

INSERT INTO Flows
(Product, Inbound_Date, Outbound_Date, Return_Date, Quantity)
VALUES

("Product A", "2019-01-01", NULL, NULL, "400"),
("Product A", NULL, "2019-05-08", NULL, "200"),
("Product A", NULL, NULL, "2019-06-25", "600"),

("Product B", "2019-03-08", NULL, NULL, "380"),
("Product B", NULL, "2019-03-15", NULL, "120"),
("Product B", NULL, NULL, "2019-04-17", "610");

I use the following SQL to get the values from the table:

SELECT Product, Inbound_Date, Outbound_Date, Return_Date, sum(Quantity)
FROM Flows
GROUP BY 1,2,3,4;

All this works fine so far.

However, now I want to achieve that the dates are displayed in one column called FLow_Date.

The result should look like this:

Product          Date_Type            Flow_Date
Product A        Inbound_Date        2019-01-01
Product A        Oubound_Date        2019-05-08
Product A        Return_Date         2019-06-25
Product B        Inbound_Date        2019-03-08
Product B        Outbound_Date       2019-03-15
Product B        Return_Date         2019-04-17

What do I need to change in my code to make it work?

Body:
I think you just need case expressions:

select f.product,
       (case when inbound_date is not null then 'inbound_date'
             when outbound_date is not null then 'outbound_date'
             when return_date is not null then 'return_date'
        end) date_type,
       (case when inbound_date is not null then inbound_date
             when outbound_date is not null then outbound_date
             when return_date is not null then return_date
        end) as flow_date
from flows f;

This becomes more complicated if you can have multiple non-NULL values per row.

In that case, union all is a simple enough approach

select fd.*
from ((select f.product, 'inbound_date' as date_type, inbound_date as flow_date
       from flows f
      ) union all
      (select f.product, 'outbound_date' as date_type, outbound_date as flow_date
       from flows f
      ) union all
      (select f.product, 'return_date' as date_type, return_date as flow_date
       from flows f
      )
     ) fd
where flow_date is not null;

This is not necessarily the most efficient method (in this case), but it works well.  If flows is really a view, then alternatives might be preferred.


答:
The reason is that objects are references to values in JavaScript. So two objects, even with the identical value are evaluated as different, since its stored as two different values. If you use the same, you get the result you expect:</p>

```<code>let myMap = new Map();
const key = {type : 'sum', val : 10}
myMap.set(key, 1);
console.log(myMap.get(key)); // 1
</code>```

Title: JavaScript map object not saving object keys?

Body:
The reason is that objects are references to values in JavaScript. So two objects, even with the identical value are evaluated as different, since its stored as two different values. If you use the same, you get the result you expect:

let myMap = new Map();
const key = {type : 'sum', val : 10}
myMap.set(key, 1);
console.log(myMap.get(key)); // 1


问:
how to render the side panel from left side?
I have  sidenav component which is being toggled from a button.
But upon being toggled it is opening from top,but i want it to open from left side.
How can I implement it?
My navigation component:

    <mat-toolbar>
        <button (click)="toggleSidenav()">
            Course Details
        </button>
    </mat-toolbar>

    <mat-sidenav-container *ngIf="open">
        <mat-sidenav></mat-sidenav>
        <mat-sidenav-content>
            <mat-list>
                <mat-list-item>Accounts</mat-list-item>
                <mat-list-item>UserProfile</mat-list-item>
                <mat-list-item>Contact me</mat-list-item>
                <mat-list-item>Gspeed</mat-list-item>
            </mat-list>
        </mat-sidenav-content>
    </mat-sidenav-container>

```

答:
You forgot the mode property in your mat-sidenav component.

<mat-sidenav mode="side">
```

<p>And all things considered, I guess you are misusing the <code>sidenav</code> component. According to the doc, you should put your list of links inside the <code>mat-sidenav</code> component. The content of <code>mat-sidenav-content</code> is instead the real content of your page. For example, your <code>app.component.html</code> could look like :</p>

<pre class="lang-html prettyprint-override"><code><mat-sidenav-container>

    <mat-sidenav>
        <mat-nav-list>
        ...
        </mat-nav-list>
    </mat-sidenav>

    <mat-sidenav-content>
        <router-outlet></router-outlet>
    </mat-sidenav-content>

</mat-sidenav-container>
</code>```

Body:
You forgot the mode property in your mat-sidenav component.

<mat-sidenav mode="side">

And all things considered, I guess you are misusing the sidenav component. According to the doc, you should put your list of links inside the mat-sidenav component. The content of mat-sidenav-content is instead the real content of your page. For example, your app.component.html could look like :

<mat-sidenav-container>

    <mat-sidenav>
        <mat-nav-list>
        ...
        </mat-nav-list>
    </mat-sidenav>

    <mat-sidenav-content>
        <router-outlet></router-outlet>
    </mat-sidenav-content>

</mat-sidenav-container>


问:
Strategy to refactor when too many dependencies injected into service or controller
I have an ASP.NET MVC 1 application that uses NHibernate and Castle Windsor for IoC. The controllers have service classes injected, and these service classes handle all the logic and actions required by the app. The service classes have repositories injected. Each repository handles a single object. Objects are mapped to DB table via NH. I have tried to keep a one to one relationship between services and controllers, but some services are used in more than one controller.

The problem is that some services now have dependencies on 10-15 repositories. The system has an invoicing component for example, where certain actions depend on users, customers, work orders, work order line items, invoices, invoice line items, taxes, etc.

What strategies do people used to refactor effectively when it comes to dependency overload? I'm thinking of splitting one service into many services and to remove the 1-to-1 attempt between services and controllers. But then dependencies at the controller level will increase. Splitting one controller into many controllers is possible with the prior suggestion, but I don't believe that's done unless you break views into partial views? I realize this is a broad question, but I'm more looking for guidance than exact answers. Feel free to provide links to articles or examples of similar refactoring.

答:
You should refactor to Facade Services, which involves sliding in a new layer of more coarse-grained services that orchestrate the finer-grained services. Currently your Controllers are doing too much fine-grained work.

FWIW chapter 6 of my book contains an example of this process and it also touches on some of the mental exercises you can do to identify the appropriate clusters of services to be grouped.

Keep in mind that a particular service can be a member of more than one cluster. That basically just indicates that this is a central service in the application.

ContentLicense: CC BY-SA 3.0


问:
OpenSSL TLS Server - use client certificate whitelist
I am developing a C++ client/server application that uses OpenSSL.
The server uses a whitelist in order to accept only certain clients.

On the server, I generate a self-signed root certificate (rootCA.pem), which is also used as the server certificate. (I will use a separate server certificate in the future, this is describing my application now).
Clients generate CSRs which are signed by the server using the root certificate (rootCA.pem). These client certificates are then sent to clients to be used by them and also placed in the "clientCertificate" folder.
I am trying to accept a connection from an approved client, but it is not working.

```<code>SSL_CTX_use_certificate_file(ctx, "rootCA.pem", SSL_FILETYPE_PEM);
SSL_CTX_use_PrivateKey_file(ctx, "serverPrivateKey.pem", SSL_FILETYPE_PEM);
STACK_OF(X509_NAME) *list;
list = SSL_load_client_CA_file("rootCA.pem");
SSL_CTX_set_client_CA_list(ctx, list);
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
SSL_CTX_load_verify_locations(ctx, NULL, "clientCertificate")
</code>```

Is there an obvious mistake that I have made?

If I only use the first two lines (only SSL_CTX_use_certificate_file and SSL_CTX_use_PrivateKey_file) and comment the others, the application works.

The "rootCA.pem" has the digitalSignature keyUsage field.

An additional question would be, suppose I get the handshake working, how do I then disconnect clients by simplify removing its certificate from the "clientCertificatesFolder"? Is there a "check if client is still approved" function from OpenSSL that I can use?

答:
Usually a server does not need to know certificates of clients before connection attempts.
A server can do TLS client authentication by using the trusted CA certificate.

```<code>SSL_CTX_load_verify_locations(ctx, "rootCA.pem", NULL)
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, callback);
</code>```

This way the TLS server accepts only clients, that have a valid certificate chain and the correct private key of the client certificate. (=root certificate of the certificate chain must be in "rootCA.pem").

If some kind of white list is still really needed, you can implement it in callback function.

Body:
I am developing a C++ client/server application that uses OpenSSL.
The server uses a whitelist in order to accept only certain clients.

On the server, I generate a self-signed root certificate (rootCA.pem), which is also used as the server certificate. (I will use a separate server certificate in the future, this is describing my application now).
Clients generate CSRs which are signed by the server using the root certificate (rootCA.pem). These client certificates are then sent to clients to be used by them and also placed in the "clientCertificate" folder.
I am trying to accept a connection from an approved client, but it is not working.

SSL_CTX_use_certificate_file(ctx, "rootCA.pem", SSL_FILETYPE_PEM);
SSL_CTX_use_PrivateKey_file(ctx, "serverPrivateKey.pem", SSL_FILETYPE_PEM);
STACK_OF(X509_NAME) *list;
list = SSL_load_client_CA_file("rootCA.pem");
SSL_CTX_set_client_CA_list(ctx, list);
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
SSL_CTX_load_verify_locations(ctx, NULL, "clientCertificate")

Is there an obvious mistake that I have made?

If I only use the first two lines (only SSL_CTX_use_certificate_file and SSL_CTX_use_PrivateKey_file) and comment the others, the application works.

The "rootCA.pem" has the digitalSignature keyUsage field.

An additional question would be, suppose I get the handshake working, how do I then disconnect clients by simplify removing its certificate from the "clientCertificatesFolder"? Is there a "check if client is still approved" function from OpenSSL that I can use?

Body:
Usually a server does not need to know certificates of clients before connection attempts.
A server can do TLS client authentication by using the trusted CA certificate.

SSL_CTX_load_verify_locations(ctx, "rootCA.pem", NULL)
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, callback);

This way the TLS server accepts only clients, that have a valid certificate chain and the correct private key of the client certificate. (=root certificate of the certificate chain must be in "rootCA.pem").

If some kind of white list is still really needed, you can implement it in callback function.


问:
HOST is not recognized as an internal or external command
After cloning a Git repo with a ReactJS and NodeJS project and install NodeJS

wanted to see the result in the browser and for that had to run in the root folder which had a package.json

npm install

and after

npm start

First command worked fine but the second was giving the following error

```<code>> HOST=0.0.0.0 PORT=8000 ./node_modules/.bin/react-scripts start
'HOST' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ...: `HOST=0.0.0.0 PORT=8000 ./node_modules/.bin/react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ... start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
</code>```

The package.json has the following

```<code>"scripts": {
  "start": "HOST=0.0.0.0 PORT=8000 ./node_modules/.bin/react-scripts start",
</code>```

Tested using Git Bash, CMD and PowerShell and kept on getting the same error, as you can see in the following images

Git Bash

CMD

PowerShell

答:
Method 1

If I run (without using the npm wrapper script)

```<code>HOST=0.0.0.0 PORT=8000 ./node_modules/.bin/react-scripts start
</code>```

it works fine. As Quentin says,

Must be something to do with how npm shells out then

To fix it, I've gone to package.json and changed the "start" script to

```<code>"start": "./node_modules/.bin/react-scripts start",
</code>```

Then npm start works fine.

Method 2

Use the cross-env package.

For that install it using the following command

```<code>npm i cross-env
</code>```

then go to package.json and change it to

```<code>"start": "cross-env ./node_modules/.bin/react-scripts start",
</code>```

And then running npm start will also work fine:

Body:
After cloning a Git repo with a ReactJS and NodeJS project and install NodeJS

wanted to see the result in the browser and for that had to run in the root folder which had a package.json

npm install

and after

npm start

First command worked fine but the second was giving the following error

> HOST=0.0.0.0 PORT=8000 ./node_modules/.bin/react-scripts start
'HOST' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ...: `HOST=0.0.0.0 PORT=8000 ./node_modules/.bin/react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ... start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:

The package.json has the following

"scripts": {
  "start": "HOST=0.0.0.0 PORT=8000 ./node_modules/.bin/react-scripts start",

Tested using Git Bash, CMD and PowerShell and kept on getting the same error, as you can see in the following images

Git Bash

CMD

PowerShell

Body:
Method 1

If I run (without using the npm wrapper script)

HOST=0.0.0.0 PORT=8000 ./node_modules/.bin/react-scripts start

it works fine. As Quentin says,

Must be something to do with how npm shells out then

To fix it, I've gone to package.json and changed the "start" script to

"start": "./node_modules/.bin/react-scripts start",

Then npm start works fine.

Method 2

Use the cross-env package.

For that install it using the following command

npm i cross-env

then go to package.json and change it to

"start": "cross-env ./node_modules/.bin/react-scripts start",

And then running npm start will also work fine:


问:
getting segmentation fault(core dump)after typing all the value in a vector in c++
i have made this code to print a string and int.

```<code> vector<int> nu;

for(int v;cin>>v;)
    nu.push_back(v);

vector<string> la;
for(string c;cin>>c;)
    la.push_back(c);
</code>```

the programme runs and starts taking value but as i put anything other than int to stop the

```<code>for(int v;cin>>v;)
</code>```

part i get segmentation fault.all variables are defined locally so i do not understand why i am getting this error.

EDIT: for printing i have created a function

```<code>void print(vector<string> a,vector<int> b)
{int y=0;
y= b.size();
for(int i=0;i<y;i++)
    {cout<<a[i]<<" "<<b[i]<<"\n";
     }

}
</code>```

答: You should not access vectors before you have checked their size. You only check vector b but also access vector a which is likely empty because the input failed (because you didn't clear the stream after you entered something that could not be parsed as an int, so the second input loop was never entered).

Body:
i have made this code to print a string and int.

 vector<int> nu;

for(int v;cin>>v;)
    nu.push_back(v);

vector<string> la;
for(string c;cin>>c;)
    la.push_back(c);

the programme runs and starts taking value but as i put anything other than int to stop the

for(int v;cin>>v;)

part i get segmentation fault.all variables are defined locally so i do not understand why i am getting this error.

EDIT: for printing i have created a function

void print(vector<string> a,vector<int> b)
{int y=0;
y= b.size();
for(int i=0;i<y;i++)
    {cout<<a[i]<<" "<<b[i]<<"\n";
     }

}