问:
how to save data in the background every 2 minutes in Laravel
we're making a web app that's supposed to save the patient's viral signs history in the database, like every two minutes or so in the background. is it possible to do that in laravel if so how can i do it?</p>

答:
I recommend using job:

php artisan make:job PatientViralSignsJob

this command will generate class PatientViralSignsJob in app\Jobs folder.

in the PatientViralSignsJob ... hande() method you could write your logic

```<code>public function handle()
{
   // write your code here ...
}
</code>```

finally register your job class in Console\Kernel.php in schedule method:

```<code>  protected function schedule(Schedule $schedule)
    {
         $schedule->job(new PatientViralSignsJob())->everyFiveMinutes();
    }
</code>```

this will make your handle method in PatientViralSignsJob executed every five minutes

more details in:

https://laravel.com/docs/7.x/queues#creating-jobs

Body:
I recommend using job:

php artisan make:job PatientViralSignsJob

this command will generate class PatientViralSignsJob in app\Jobs folder.

in the PatientViralSignsJob ... hande() method you could write your logic

public function handle()
{
   // write your code here ...
}

finally register your job class in Console\Kernel.php in schedule method:

  protected function schedule(Schedule $schedule)
    {
         $schedule->job(new PatientViralSignsJob())->everyFiveMinutes();
    }

this will make your handle method in PatientViralSignsJob executed every five minutes

more details in:

https://laravel.com/docs/7.x/queues#creating-jobs


来源: stackexchange

问:
Template metaprogramming to match function signature exactly
With template meta-programming it's possible to query properties of types. For example in the case below I'm checking if a certain type has a member function "foo" which takes in another type as the argument.

Is there a way to check if the parameter type is an exact match for the template vs. one that be converted to it, e.g. double or char can be converted into float (causing main to print true twice) but I'm trying to see if there is a way to structure my_test_t so that it matches perfectly, i.e. main() prints false unless T2 = float.

```<code>struct S2
{
   int foo(float x)
   {
      return 0;
   }
};

template <typename T1, typename T2>
using my_test_t = decltype(declval<T1>().foo(declval<T2>()));

template <typename T1, typename T2, typename = void>
struct is_formed : std::false_type
{
};

template <typename T1, typename T2>
struct is_formed<T1, T2, void_t<my_test_t<T1, T2>>> : std::true_type
{
};

int main()
{
   cout << boolalpha << is_formed<S2, double>::value << endl;
   cout << boolalpha << is_formed<S2, char>::value << endl;
}
</code>```

答:
You can try to use std::is_same to match exact types for foos arguments, for a start you would have to define a type in the struct to compare with.

There could be a better way, I wouldnt know off hand.

ContentLicense: CC BY-SA 4.0

Body:
With template meta-programming it's possible to query properties of types. For example in the case below I'm checking if a certain type has a member function "foo" which takes in another type as the argument.

Is there a way to check if the parameter type is an exact match for the template vs. one that be converted to it, e.g. double or char can be converted into float (causing main to print true twice) but I'm trying to see if there is a way to structure my_test_t so that it matches perfectly, i.e. main() prints false unless T2 = float.

struct S2
{
   int foo(float x)
   {
      return 0;
   }
};

template <typename T1, typename T2>
using my_test_t = decltype(declval<T1>().foo(declval<T2>()));

template <typename T1, typename T2, typename = void>
struct is_formed : std::false_type
{
};

template <typename T1, typename T2>
struct is_formed<T1, T2, void_t<my_test_t<T1, T2>>> : std::true_type
{
};

int main()
{
   cout << boolalpha << is_formed<S2, double>::value << endl;
   cout << boolalpha << is_formed<S2, char>::value << endl;
}


问:
Mooc Helsinki Part 1 Week 4 Exercise 18 Java
The program described here should be implemented in the class PersonalInformationCollection. NB! Do not modify the class PersonalInformation.

After the user has entered the last set of details (they enter an empty first name), exit the repeat statement.

Then print the collected personal information so that each entered object is printed in the following format: first and last names separated by a space (you don't print the identification number). An example of the working program is given below:

```<code>Sample output
First name: Jean
Last name: Bartik
Identification number: 271224
First name: Betty
Last name: Holberton
Identification number: 070317
First name:

Jean Bartik
Betty Holberton
</code>```

The PersonalInformation class:

```<code>public class PersonalInformation {

    private String firstName;
    private String lastName;
    private String identificationNumber;

    public PersonalInformation(String firstName, String lastName, String identificationNumber) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.identificationNumber = identificationNumber;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getIdentificationNumber() {
        return identificationNumber;
    }

    @Override
    public String toString() {
        return this.lastName + ", " + this.firstName + " (" + this.identificationNumber + ")";
    }
}
</code>```

My solution which I can only print all values instead of only Firstnames and the Lastnames from the array:

```<code>public class Main {

    public static void main(String[] args) {
        // write your code here
        Scanner scanner = new Scanner(System.in);
        ArrayList<PersonalInformation> infoCollection = new ArrayList<>();

        while (true) {
            System.out.println("First name: ");
            String firstName = scanner.nextLine();
            if (firstName.equals("")) {
                break;
            }
            System.out.println("Last name: ");
            String lastName = scanner.nextLine();
            System.out.println("Identification number: ");
            String identificationNumber = scanner.nextLine();

            infoCollection.add(new PersonalInformation(firstName, lastName, identificationNumber));

        }
        System.out.println(infoCollection);

    }

}
</code>```

I need to modify the code. I am a beginner, an explanatory suggestion would be much appreciated.

答:
Instead of

```<code>System.out.println(infoCollection);
</code>```

you´ll have

```<code>infoCollection.stream().forEach(p -> System.out.println(p.getFirstName() + " " + p.getLastName()));
</code>```

Body:
The program described here should be implemented in the class PersonalInformationCollection. NB! Do not modify the class PersonalInformation.

After the user has entered the last set of details (they enter an empty first name), exit the repeat statement.

Then print the collected personal information so that each entered object is printed in the following format: first and last names separated by a space (you don't print the identification number). An example of the working program is given below:

Sample output
First name: Jean
Last name: Bartik
Identification number: 271224
First name: Betty
Last name: Holberton
Identification number: 070317
First name:

Jean Bartik
Betty Holberton

The PersonalInformation class:

public class PersonalInformation {

    private String firstName;
    private String lastName;
    private String identificationNumber;

    public PersonalInformation(String firstName, String lastName, String identificationNumber) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.identificationNumber = identificationNumber;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getIdentificationNumber() {
        return identificationNumber;
    }

    @Override
    public String toString() {
        return this.lastName + ", " + this.firstName + " (" + this.identificationNumber + ")";
    }
}

My solution which I can only print all values instead of only Firstnames and the Lastnames from the array:

public class Main {

    public static void main(String[] args) {
        // write your code here
        Scanner scanner = new Scanner(System.in);
        ArrayList<PersonalInformation> infoCollection = new ArrayList<>();

        while (true) {
            System.out.println("First name: ");
            String firstName = scanner.nextLine();
            if (firstName.equals("")) {
                break;
            }
            System.out.println("Last name: ");
            String lastName = scanner.nextLine();
            System.out.println("Identification number: ");
            String identificationNumber = scanner.nextLine();

            infoCollection.add(new PersonalInformation(firstName, lastName, identificationNumber));

        }
        System.out.println(infoCollection);

    }

}

I need to modify the code. I am a beginner, an explanatory suggestion would be much appreciated.

Body:
Instead of

System.out.println(infoCollection);

you´ll have

infoCollection.stream().forEach(p -> System.out.println(p.getFirstName() + " " + p.getLastName()));


问:
Unable to fetch all the links from a webpage using requests
I'm trying to get all the links connected to each image in this webpage.

I can get all the links if I let a selenium script scroll downward until it reaches the bottom. One such link that I wish to scrape is this one.

Now, my goal here is to parse all those links using requests. What I have notice that the links that I want to parse are built using such B-uPwZsJtnB shortcode.

However,
I'm trying to scrape those different shortcode available in a script tag found in page source in that webpage. There are around 600 shortcodes in that page. The script that I've created can parse only the first 70 such shortcode which ultimately can built 70 qualified links.

How can I grab all 600 links using requests?

I've tried so far with:

```<code>import re
import json
import requests

base_link = 'https://www.instagram.com/p/{}/'
lead_url = 'https://www.instagram.com/explore/tags/baltimorepizza/'

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
    req = s.get(lead_url)
    script_tag = re.findall(r"window\._sharedData[^{]+(.*?);",req.text)[0]
    for item in json.loads(script_tag)['entry_data']['TagPage']:
        tag_items = item['graphql']['hashtag']['edge_hashtag_to_media']['edges']
        for elem in tag_items:
            profile_link = base_link.format(elem['node']['shortcode'])
            print(profile_link)
</code>```

答:
The Instagram web page uses lazy loading to load the images. You can overcome this in 2 ways:

Use the Instagram API as mentioned in the comments

Use a tool like selenium to load all the images on the page by scrolling to the bottom and then fetch the links

The 1st method is be the better way to do it.

Body:
I'm trying to get all the links connected to each image in this webpage.

I can get all the links if I let a selenium script scroll downward until it reaches the bottom. One such link that I wish to scrape is this one.

Now, my goal here is to parse all those links using requests. What I have notice that the links that I want to parse are built using such B-uPwZsJtnB shortcode.

However,
I'm trying to scrape those different shortcode available in a script tag found in page source in that webpage. There are around 600 shortcodes in that page. The script that I've created can parse only the first 70 such shortcode which ultimately can built 70 qualified links.

How can I grab all 600 links using requests?

I've tried so far with:

import re
import json
import requests

base_link = 'https://www.instagram.com/p/{}/'
lead_url = 'https://www.instagram.com/explore/tags/baltimorepizza/'

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
    req = s.get(lead_url)
    script_tag = re.findall(r"window\._sharedData[^{]+(.*?);",req.text)[0]
    for item in json.loads(script_tag)['entry_data']['TagPage']:
        tag_items = item['graphql']['hashtag']['edge_hashtag_to_media']['edges']
        for elem in tag_items:
            profile_link = base_link.format(elem['node']['shortcode'])
            print(profile_link)


问:
Read a Text file having row in parenthesis and values separated by comma using pandas
I want to read a text file which contains data in parenthesis as row and values in it as column.The format of txt file is below :

```<code>(a, b, c, d) (a1, b1, (c1,c12,c13), d1) (a2, b2, (c2,c22,c23), d2) (a3, b3, (c3,c32,c33), d3) (a4, b4, (c4,c42,c43), d4)
</code>```

I want the data in this format :

```<code>a  b  c  d
a1 b1 c1 d1
a2 b2 c2 d2
a3 b3 c3 d3
a4 b4 c4 d4
</code>```

When i am reading text file as csv file it reads all the data in one row only. It shows 1 row and all the columns.
Please help me with this problem.

答:
With builtin pandas functions (perhaps faster with large dataframe), you can use:

# Use the standard `read_csv` function of pandas.
# Note the lineterminator option.
df = pd.read_csv('data.dat', sep=",", lineterminator=")")
# rename the 1st column (remove 1st char)
df.columns.values[0] = df.columns.values[0][1:]
# remove the opening parenthesis for the 1st columns:
df.iloc[:, 0] = df.iloc[:, 0].str.replace('^\ ?\(', '')
# remove the last line:
df = df[:-1]
print(df)
```

Body:
I want to read a text file which contains data in parenthesis as row and values in it as column.The format of txt file is below :

(a, b, c, d) (a1, b1, (c1,c12,c13), d1) (a2, b2, (c2,c22,c23), d2) (a3, b3, (c3,c32,c33), d3) (a4, b4, (c4,c42,c43), d4)

I want the data in this format :

a  b  c  d
a1 b1 c1 d1
a2 b2 c2 d2
a3 b3 c3 d3
a4 b4 c4 d4

When i am reading text file as csv file it reads all the data in one row only. It shows 1 row and all the columns.
Please help me with this problem.


问:
SQLAlchemy One to Many relationship mapping/joining error
I want to create a relationship between speaker and records.
A speaker can have multiple records

but the error below was shown:

sqlalchemy.exc.InvalidRequestError: Class
  does not have a mapped column named 'speaker_id'

Speaker Model:

```<code>class Speaker(Base):
    __tablename__ = 'speakers'
    id       = db.Column(db.Integer,     primary_key=True)
    cin      = db.Column(db.String(8),  unique = True)
    nom      = db.Column(db.String(64))
    prenom   = db.Column(db.String(64))
    adresse  = db.Column(db.String(120))
    datedn   = db.Column(db.String(20))
    genre    = db.Column(db.String(64))
    phone    = db.Column(db.Boolean, default=False)
    profession = db.Column(db.String(120))
    records  = db.relationship('Record', backref="owner", primaryjoin="Speaker.id==Record.speaker_id")
    created  = db.Column(db.DateTime, default=datetime.datetime.utcnow)
</code>```

Record Model:

```<code>class Record(Base):
    __tablename__ = 'record'
    id       = db.Column(db.Integer, primary_key=True)
    path     = db.Column(db.String(500))
    created  = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    speaker_id = db.column(db.Integer, db.ForeignKey('speakers.id'))
</code>```

I Have tried the relationship without primaryjoin but I had this error:

sqlalchemy.exc.NoForeignKeysError: Could not determine join condition
  between parent/child tables on relationship Speaker.records - there
  are no foreign keys linking these tables.  Ensure that referencing
  columns are associated with a ForeignKey or ForeignKeyConstraint, or
  specify a 'primaryjoin' expression.

what am I missing here ?

答: This is a bit of a typo, but something that pops up every now and then: the c in "column" has to be capitalized in 6th line of the Record class (on the speaker id line). </p>

Body:
I want to create a relationship between speaker and records.
A speaker can have multiple records

but the error below was shown:

sqlalchemy.exc.InvalidRequestError: Class
  does not have a mapped column named 'speaker_id'

Speaker Model:

class Speaker(Base):
    __tablename__ = 'speakers'
    id       = db.Column(db.Integer,     primary_key=True)
    cin      = db.Column(db.String(8),  unique = True)
    nom      = db.Column(db.String(64))
    prenom   = db.Column(db.String(64))
    adresse  = db.Column(db.String(120))
    datedn   = db.Column(db.String(20))
    genre    = db.Column(db.String(64))
    phone    = db.Column(db.Boolean, default=False)
    profession = db.Column(db.String(120))
    records  = db.relationship('Record', backref="owner", primaryjoin="Speaker.id==Record.speaker_id")
    created  = db.Column(db.DateTime, default=datetime.datetime.utcnow)

Record Model:

class Record(Base):
    __tablename__ = 'record'
    id       = db.Column(db.Integer, primary_key=True)
    path     = db.Column(db.String(500))
    created  = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    speaker_id = db.column(db.Integer, db.ForeignKey('speakers.id'))

I Have tried the relationship without primaryjoin but I had this error:

sqlalchemy.exc.NoForeignKeysError: Could not determine join condition
  between parent/child tables on relationship Speaker.records - there
  are no foreign keys linking these tables.  Ensure that referencing
  columns are associated with a ForeignKey or ForeignKeyConstraint, or
  specify a 'primaryjoin' expression.

what am I missing here ?


问:
React Native - Set a simple variable for useSelector
I need to set a variable to use with useSelector (redux), and looks pretty simple but I don't know how to do it.

```<code>  const CATEGORY = cat;
  console.log(CATEGORY); // correctly get the strings 'food' or 'design'

  const getItems = useSelector(state => state.appDb.CATEGORY);
  console.log(getItems); // I get undefined
</code>```

basically I would like to use the variable to set this:

state.appDb.food or state.appDb.design

What would be the correct syntax?

答:
All you need to use to brackets notation to access dynamic object keys like

```<code>  const CATEGORY = cat;
  console.log(CATEGORY); // correctly get the strings 'food' or 'design'

  const getItems = useSelector(state => state.appDb[CATEGORY]);
  console.log(getItems);
</code>```

Body:
I need to set a variable to use with useSelector (redux), and looks pretty simple but I don't know how to do it.

  const CATEGORY = cat;
  console.log(CATEGORY); // correctly get the strings 'food' or 'design'

  const getItems = useSelector(state => state.appDb.CATEGORY);
  console.log(getItems); // I get undefined

basically I would like to use the variable to set this:

state.appDb.food or state.appDb.design

What would be the correct syntax?

Body:
All you need to use to brackets notation to access dynamic object keys like

  const CATEGORY = cat;
  console.log(CATEGORY); // correctly get the strings 'food' or 'design'

  const getItems = useSelector(state => state.appDb[CATEGORY]);
  console.log(getItems);


问:
How do I execute python code from yml file?
I decided to store my python app configurations in yml file.
My yml file looks something like this:

config.yml

name: firstApp
base_dir: "Path(__file__).resolve(strict=True).parent.parent"
secret_key: "a passphrase for peppering"
mysql:
    host: localhost
    user: root
    passwd: "my secret password"
```
<p>I then import the yml file using pyyaml library:</p>
<h1>config.py</h1>
<pre class="lang-py prettyprint-override"><code>import yaml
config = yaml.safe_load(open('path/to/config.yml'))
</code>```

currently config.base_dir returns  Path(__file__).resolve(strict=True).parent.parent but I want it to return the output of the python code which relies on running from pathlib import Path first.

using eval and exec is frowned upon. But I do not see any other way around it. Looking for some guidance and a way to do this without any security concerns.

Thanks,

答:
By definition, running code from within a text file which is writable by external entities, is a potential security hazard. The traditional way to try and support such things is to run the code in a "sandbox" (a restricted environment with limited permissions), however that's not exactly trivial (see some basic details here and a more complete answer in Software Engineering Stack Exchange) - unless you can define very accurate permissions of what the code should and should not be able to do, this is going to be a configuration headache, which is going to be very OS specific.

When I need similar configs to what you presented, usually I define tokens such as {current_file_path} and other magic values and interpret them when they appear in strings - in your case it would be {current_file_path}/../.. which would obtain the same result as the proposed code (assuming you do resolve the path).

If you can define a list of the capabilities you do wish to support, it would possibly enable providing a more secure solution for your usecase.

Body:
I decided to store my python app configurations in yml file.
My yml file looks something like this:

config.yml

name: firstApp
base_dir: "Path(__file__).resolve(strict=True).parent.parent"
secret_key: "a passphrase for peppering"
mysql:
    host: localhost
    user: root
    passwd: "my secret password"

I then import the yml file using pyyaml library:

config.py

import yaml
config = yaml.safe_load(open('path/to/config.yml'))

currently config.base_dir returns  Path(__file__).resolve(strict=True).parent.parent but I want it to return the output of the python code which relies on running from pathlib import Path first.

using eval and exec is frowned upon. But I do not see any other way around it. Looking for some guidance and a way to do this without any security concerns.

Thanks,


问:
How to authenticate SockJS CONNECT with JWT in Spring
I am trying to connect to a topic with SockJS, but the response I get is 401 Unauthorized. The project contains Spring security with JWT Authentication. Searching through internet I found that I should authenticate the user in a interceptor. The problem is that my interceptor is not reached.

Everything works fine in a POC (proof of concept) application without Spring security.

I hope I described the problem properly, thanks in advance.

The interceptor that authenticates the user:

```<code>@Component
@RequiredArgsConstructor
public class SocketAuthenticationInterceptor implements ChannelInterceptor {
    private final JwtTokenProvider tokenProvider;
    private final UserDetailsServiceImpl userDetailsService;

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
                    StompHeaderAccessor accessor =
                            MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                    if (StompCommand.CONNECT.equals(accessor.getCommand())) {
                        List<String> authorization = accessor.getNativeHeader("Authorization");
                        String jwt = authorization.get(0);
                        final Integer userId = tokenProvider.getUserIdFromJWT(jwt);

                        final UserDetails userDetails = userDetailsService.loadUserById(userId);
                        final UsernamePasswordAuthenticationToken authentication =
                                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        accessor.setUser(authentication);
                    }
                    return message;
    }
}
</code>```

Registering the interceptor:

```<code>@Configuration
@RequiredArgsConstructor
@EnableWebSocketMessageBroker
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
public class WebSocketAuthenticationConfig implements WebSocketMessageBrokerConfigurer {

    private final SocketAuthenticationInterceptor socketAuthenticationInterceptor;

    @Override
    public void configureClientInboundChannel(final ChannelRegistration registration) {
        registration.interceptors(socketAuthenticationInterceptor);
    }
}
</code>```

答:
Authenticating the user for a web request is done using filters in Springboot. By default there are a bunch of filters which try to authenticate any request. Note that this authentication is done during the handshake and before sending the initial CONNECT message. A CustomInterceptor is used for handling the messages we receive not for AuthN, since the filter itself is unauthn'ing the request the message is not even being received hence the execution is not reaching the interceptor.
So instead write your own custom filter class like so

```<code>class JwtRequestFilter extends OncePerRequestFilter {
...
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
String requestTokenHeader = request.getHeader("Authorization");
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
                jwtToken = requestTokenHeader.substring(7);
 }
final Integer userId = tokenProvider.getUserIdFromJWT(jwtToken);
final UserDetails userDetails = userDetailsService.loadUserById(userId);
final UsernamePasswordAuthenticationToken authentication =new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
//If you want to set source details
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
   }
}
</code>```

And then add this custom filter to the list of filters like so in WebSecurityConfig.java

```<code> @Override
 protected void configure(HttpSecurity httpSecurity) throws Exception {
  ...
   // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); // Or any other filter of your choice
 }
</code>```

So with this your authentication context is set.
Useful Links:

Spring Security Architecture

Adding Custom Filter in SpringBoot

More on Web Security in Spring

Bearer schema JWT Token

Body:
I am trying to connect to a topic with SockJS, but the response I get is 401 Unauthorized. The project contains Spring security with JWT Authentication. Searching through internet I found that I should authenticate the user in a interceptor. The problem is that my interceptor is not reached.

Everything works fine in a POC (proof of concept) application without Spring security.

I hope I described the problem properly, thanks in advance.

The interceptor that authenticates the user:

@Component
@RequiredArgsConstructor
public class SocketAuthenticationInterceptor implements ChannelInterceptor {
    private final JwtTokenProvider tokenProvider;
    private final UserDetailsServiceImpl userDetailsService;

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
                    StompHeaderAccessor accessor =
                            MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                    if (StompCommand.CONNECT.equals(accessor.getCommand())) {
                        List<String> authorization = accessor.getNativeHeader("Authorization");
                        String jwt = authorization.get(0);
                        final Integer userId = tokenProvider.getUserIdFromJWT(jwt);

                        final UserDetails userDetails = userDetailsService.loadUserById(userId);
                        final UsernamePasswordAuthenticationToken authentication =
                                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        accessor.setUser(authentication);
                    }
                    return message;
    }
}

Registering the interceptor:

@Configuration
@RequiredArgsConstructor
@EnableWebSocketMessageBroker
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
public class WebSocketAuthenticationConfig implements WebSocketMessageBrokerConfigurer {

    private final SocketAuthenticationInterceptor socketAuthenticationInterceptor;

    @Override
    public void configureClientInboundChannel(final ChannelRegistration registration) {
        registration.interceptors(socketAuthenticationInterceptor);
    }
}

Body:
Authenticating the user for a web request is done using filters in Springboot. By default there are a bunch of filters which try to authenticate any request. Note that this authentication is done during the handshake and before sending the initial CONNECT message. A CustomInterceptor is used for handling the messages we receive not for AuthN, since the filter itself is unauthn'ing the request the message is not even being received hence the execution is not reaching the interceptor.
So instead write your own custom filter class like so

class JwtRequestFilter extends OncePerRequestFilter {
...
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
String requestTokenHeader = request.getHeader("Authorization");
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
                jwtToken = requestTokenHeader.substring(7);
 }
final Integer userId = tokenProvider.getUserIdFromJWT(jwtToken);
final UserDetails userDetails = userDetailsService.loadUserById(userId);
final UsernamePasswordAuthenticationToken authentication =new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
//If you want to set source details
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
   }
}

And then add this custom filter to the list of filters like so in WebSecurityConfig.java

 @Override
 protected void configure(HttpSecurity httpSecurity) throws Exception {
  ...
   // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); // Or any other filter of your choice
 }

So with this your authentication context is set.
Useful Links:

Spring Security Architecture

Adding Custom Filter in SpringBoot

More on Web Security in Spring

Bearer schema JWT Token


问:
Generate random number that does not exist
Is there a simple way to generate a random number between 1 and 99999 that does not yet exist in the database?

I have a table called Board and one of the columns is Number.

I need to generate a new number randomly that does not yet exist as Board.Number.

答:
One possible approach is the following statement (using a number table with 100000 rows and an appropriate join):

Table:

```<code>CREATE TABLE Board ([Number] int)
INSERT INTO Board ([Number]) VALUES (1), (2), (4), (6008)
</code>```

Statement:

```<code>;WITH TallyCTE AS (
   SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS [Number]
   FROM (VALUES (1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) a(n)
   CROSS APPLY (VALUES (1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) b(n)
   CROSS APPLY (VALUES (1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) c(n)
   CROSS APPLY (VALUES (1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) d(n)
   CROSS APPLY (VALUES (1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) e(n)
)
SELECT TOP 1 t.[Number]
FROM TallyCte t
LEFT OUTER JOIN Board b ON b.[Number] = t.[Number]
WHERE (t.[Number] <= 99999) AND (b.[Number] IS NULL)
ORDER BY NEWID()
</code>```

Body:
One possible approach is the following statement (using a number table with 100000 rows and an appropriate join):

Table:

CREATE TABLE Board ([Number] int)
INSERT INTO Board ([Number]) VALUES (1), (2), (4), (6008)

Statement:

;WITH TallyCTE AS (
   SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS [Number]
   FROM (VALUES (1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) a(n)
   CROSS APPLY (VALUES (1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) b(n)
   CROSS APPLY (VALUES (1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) c(n)
   CROSS APPLY (VALUES (1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) d(n)
   CROSS APPLY (VALUES (1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) e(n)
)
SELECT TOP 1 t.[Number]
FROM TallyCte t
LEFT OUTER JOIN Board b ON b.[Number] = t.[Number]
WHERE (t.[Number] <= 99999) AND (b.[Number] IS NULL)
ORDER BY NEWID()


问:
How to inject custom SSL certs into springbok bootBuildImage
I'm not sure if this is possible w/out making a custom base image to use but I'm trying to build images behind a corporate firewall with self-signed SSL certs:

```<code>> Task :bootBuildImage
Caching disabled for task ':bootBuildImage' because:
  Build cache is disabled
Task ':bootBuildImage' is not up-to-date because:
  Task has not declared any outputs despite executing actions.
Building image 'docker.io/library/temp:latest'

 > Pulling builder image 'gcr.io/paketo-buildpacks/builder:base-platform-api-0.3' ..................................................
 > Pulled builder image 'gcr.io/paketo-buildpacks/builder@sha256:200fb7945ef0f4a3c79befb1262fd592f54ba7b7ffcc8a37716434dd11d0e5e9'
 > Pulling run image 'gcr.io/paketo-buildpacks/run:base-cnb' ..................................................
 > Pulled run image 'gcr.io/paketo-buildpacks/run@sha256:f7f27462fb513a70370322ada08440a642d24a700056d4c6b8cbb344610bf486'
 > Executing lifecycle version v0.7.5
 > Using build cache volume 'pack-cache-739c2c210811.build'

 > Running creator
    [creator]     ---> DETECTING
    [creator]     ======== Results ========
    [creator]     pass: paketo-buildpacks/bellsoft-liberica@2.7.1
    [creator]     skip: paketo-buildpacks/gradle@1.2.2
    [creator]     skip: paketo-buildpacks/maven@1.4.2
    [creator]     skip: paketo-buildpacks/sbt@1.2.2
    [creator]     pass: paketo-buildpacks/executable-jar@1.2.5
    [creator]     pass: paketo-buildpacks/apache-tomcat@1.1.5
    [creator]     pass: paketo-buildpacks/dist-zip@1.3.2
    [creator]     pass: paketo-buildpacks/spring-boot@1.5.5
    [creator]     skip: paketo-buildpacks/procfile@1.3.5
    [creator]     skip: paketo-buildpacks/azure-application-insights@1.2.1
    [creator]     skip: paketo-buildpacks/debug@1.2.5
    [creator]     skip: paketo-buildpacks/google-stackdriver@1.2.1
    [creator]     skip: paketo-buildpacks/jmx@1.1.5
    [creator]     skip: paketo-buildpacks/encrypt-at-rest@1.2.5
    [creator]     skip: paketo-buildpacks/image-labels@1.0.5
    [creator]     Resolving plan... (try #1)
    [creator]     fail: paketo-buildpacks/bellsoft-liberica@2.7.1 provides unused jdk
    [creator]     Resolving plan... (try #2)
    [creator]     skip: paketo-buildpacks/executable-jar@1.2.5 requires jre
    [creator]     skip: paketo-buildpacks/apache-tomcat@1.1.5 requires jre
    [creator]     skip: paketo-buildpacks/dist-zip@1.3.2 requires jre
    [creator]     fail: paketo-buildpacks/bellsoft-liberica@2.7.1 provides unused jdk
    [creator]     Resolving plan... (try #3)
    [creator]     5 of 15 buildpacks participating
    [creator]     paketo-buildpacks/bellsoft-liberica 2.7.1
    [creator]     paketo-buildpacks/executable-jar    1.2.5
    [creator]     paketo-buildpacks/apache-tomcat     1.1.5
    [creator]     paketo-buildpacks/dist-zip          1.3.2
    [creator]     paketo-buildpacks/spring-boot       1.5.5
    [creator]     ---> ANALYZING
    [creator]     Analyzing image "c48997fb4f4f2e07e64033a33545298861d1f71f6a11a992bbb17cc84ecefee5"
    [creator]     ---> RESTORING
    [creator]     ---> BUILDING
    [creator]
    [creator]     Paketo BellSoft Liberica Buildpack 2.7.1
    [creator]         Set $BPL_JVM_HEAD_ROOM to configure the headroom in memory calculation. Default 0.
    [creator]         Set $BPL_JVM_LOADED_CLASS_COUNT to configure the number of loaded classes in memory calculation. Default 35% of classes.
    [creator]         Set $BPL_JVM_THREAD_COUNT to configure the number of threads in memory calculation. Default 250.
    [creator]         Set $BP_JVM_VERSION to configure the Java version. Default 11.*.
    [creator]       BellSoft Liberica JRE 8.0.252: Contributing to layer
    [creator]         Downloading from https://github.com/bell-sw/Liberica/releases/download/8u252+9/bellsoft-jre8u252+9-linux-amd64.tar.gz
    [creator]     unable to invoke layer creator
    [creator]     unable to get dependency jre
    [creator]     unable to download https://github.com/bell-sw/Liberica/releases/download/8u252+9/bellsoft-jre8u252+9-linux-amd64.tar.gz
    [creator]     unable to request https://github.com/bell-sw/Liberica/releases/download/8u252+9/bellsoft-jre8u252+9-linux-amd64.tar.gz
    [creator]     Get "https://github.com/bell-sw/Liberica/releases/download/8u252+9/bellsoft-jre8u252+9-linux-amd64.tar.gz": x509: certificate signed by unknown authority
    [creator]     ERROR: failed to build: exit status 1
</code>```

Here is the log -> I'm wondering if there is a way to inject the SSL certs into the base container...

thanks

答:
Have you tried following environment variables?:

DOCKER_TLS_VERIFY Enable secure HTTPS protocol when set to 1
(optional)

DOCKER_CERT_PATH Path to certificate and key files for
HTTPS (required if DOCKER_TLS_VERIFY=1, ignored otherwise)

Reference: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/gradle-plugin/reference/html/#build-image

Body:
I'm not sure if this is possible w/out making a custom base image to use but I'm trying to build images behind a corporate firewall with self-signed SSL certs:

> Task :bootBuildImage
Caching disabled for task ':bootBuildImage' because:
  Build cache is disabled
Task ':bootBuildImage' is not up-to-date because:
  Task has not declared any outputs despite executing actions.
Building image 'docker.io/library/temp:latest'

 > Pulling builder image 'gcr.io/paketo-buildpacks/builder:base-platform-api-0.3' ..................................................
 > Pulled builder image 'gcr.io/paketo-buildpacks/builder@sha256:200fb7945ef0f4a3c79befb1262fd592f54ba7b7ffcc8a37716434dd11d0e5e9'
 > Pulling run image 'gcr.io/paketo-buildpacks/run:base-cnb' ..................................................
 > Pulled run image 'gcr.io/paketo-buildpacks/run@sha256:f7f27462fb513a70370322ada08440a642d24a700056d4c6b8cbb344610bf486'
 > Executing lifecycle version v0.7.5
 > Using build cache volume 'pack-cache-739c2c210811.build'

 > Running creator
    [creator]     ---> DETECTING
    [creator]     ======== Results ========
    [creator]     pass: paketo-buildpacks/bellsoft-liberica@2.7.1
    [creator]     skip: paketo-buildpacks/gradle@1.2.2
    [creator]     skip: paketo-buildpacks/maven@1.4.2
    [creator]     skip: paketo-buildpacks/sbt@1.2.2
    [creator]     pass: paketo-buildpacks/executable-jar@1.2.5
    [creator]     pass: paketo-buildpacks/apache-tomcat@1.1.5
    [creator]     pass: paketo-buildpacks/dist-zip@1.3.2
    [creator]     pass: paketo-buildpacks/spring-boot@1.5.5
    [creator]     skip: paketo-buildpacks/procfile@1.3.5
    [creator]     skip: paketo-buildpacks/azure-application-insights@1.2.1
    [creator]     skip: paketo-buildpacks/debug@1.2.5
    [creator]     skip: paketo-buildpacks/google-stackdriver@1.2.1
    [creator]     skip: paketo-buildpacks/jmx@1.1.5
    [creator]     skip: paketo-buildpacks/encrypt-at-rest@1.2.5
    [creator]     skip: paketo-buildpacks/image-labels@1.0.5
    [creator]     Resolving plan... (try #1)
    [creator]     fail: paketo-buildpacks/bellsoft-liberica@2.7.1 provides unused jdk
    [creator]     Resolving plan... (try #2)
    [creator]     skip: paketo-buildpacks/executable-jar@1.2.5 requires jre
    [creator]     skip: paketo-buildpacks/apache-tomcat@1.1.5 requires jre
    [creator]     skip: paketo-buildpacks/dist-zip@1.3.2 requires jre
    [creator]     fail: paketo-buildpacks/bellsoft-liberica@2.7.1 provides unused jdk
    [creator]     Resolving plan... (try #3)
    [creator]     5 of 15 buildpacks participating
    [creator]     paketo-buildpacks/bellsoft-liberica 2.7.1
    [creator]     paketo-buildpacks/executable-jar    1.2.5
    [creator]     paketo-buildpacks/apache-tomcat     1.1.5
    [creator]     paketo-buildpacks/dist-zip          1.3.2
    [creator]     paketo-buildpacks/spring-boot       1.5.5
    [creator]     ---> ANALYZING
    [creator]     Analyzing image "c48997fb4f4f2e07e64033a33545298861d1f71f6a11a992bbb17cc84ecefee5"
    [creator]     ---> RESTORING
    [creator]     ---> BUILDING
    [creator]
    [creator]     Paketo BellSoft Liberica Buildpack 2.7.1
    [creator]         Set $BPL_JVM_HEAD_ROOM to configure the headroom in memory calculation. Default 0.
    [creator]         Set $BPL_JVM_LOADED_CLASS_COUNT to configure the number of loaded classes in memory calculation. Default 35% of classes.
    [creator]         Set $BPL_JVM_THREAD_COUNT to configure the number of threads in memory calculation. Default 250.
    [creator]         Set $BP_JVM_VERSION to configure the Java version. Default 11.*.
    [creator]       BellSoft Liberica JRE 8.0.252: Contributing to layer
    [creator]         Downloading from https://github.com/bell-sw/Liberica/releases/download/8u252+9/bellsoft-jre8u252+9-linux-amd64.tar.gz
    [creator]     unable to invoke layer creator
    [creator]     unable to get dependency jre
    [creator]     unable to download https://github.com/bell-sw/Liberica/releases/download/8u252+9/bellsoft-jre8u252+9-linux-amd64.tar.gz
    [creator]     unable to request https://github.com/bell-sw/Liberica/releases/download/8u252+9/bellsoft-jre8u252+9-linux-amd64.tar.gz
    [creator]     Get "https://github.com/bell-sw/Liberica/releases/download/8u252+9/bellsoft-jre8u252+9-linux-amd64.tar.gz": x509: certificate signed by unknown authority
    [creator]     ERROR: failed to build: exit status 1

Here is the log -> I'm wondering if there is a way to inject the SSL certs into the base container...

thanks


问:
Alternating letter in python
```<code>def myfunc(word):
    result = ""
    index = 0
    for letter in word:
        if index % 2 == 0:
            result += letter.lower()
        else:
            result += letter.upper()
    return result
    index +=1
</code>```

I am trying to return a matching string where every even letter is uppercase and every odd letter is lowercase. But the code doesn't show this exact result, any solution?

答:
**

Heading

**

def myfunc(word):
    result = ""
    for index, letter in enumerate(word):
        if index % 2 == 0:
            result += letter.upper()
        else:
            result += letter.lower()
    return result

ContentLicense: CC BY-SA 3.0

Title: Alternating letter in python

Body:
def myfunc(word):
    result = ""
    index = 0
    for letter in word:
        if index % 2 == 0:
            result += letter.lower()
        else:
            result += letter.upper()
    return result
    index +=1

I am trying to return a matching string where every even letter is uppercase and every odd letter is lowercase. But the code doesn't show this exact result, any solution?


问:
Failing to authenticate to redis with Airflow Celery worker
I am trying to run Airflow Celery worker with redis backend but cant get the connection between the worker and redis to work.

Here is how the configuration looks like:

```<code>broker_url = redis://:<my-password>@localhost:6379/0
</code>```

I am getting error:

```<code>ValueError: invalid literal for int() with base 10: 'my-password-string'
</code>```

Anyone know any fix for this?

答:
So i solved it now.

My password was generated from random characters piped through base64 and it was causing problems.

I changed my password to bit shorter and simplier one and airflow worker now runs normally.

Body:
I am trying to run Airflow Celery worker with redis backend but cant get the connection between the worker and redis to work.

Here is how the configuration looks like:

broker_url = redis://:<my-password>@localhost:6379/0

I am getting error:

ValueError: invalid literal for int() with base 10: 'my-password-string'

Anyone know any fix for this?


问:
Efficient Dictionary lookup
For my C++ application, there is a requirement to check if a word is a valid English dictionary word or not. What is the best way to do it. Is there freely available dictionary that I can make use of. I just need a collection of all possible words. How to make this lookup least expensive. Do I need to hash it. </p>

答:
I actually did this a few months ago, or something close to this. You can probably find one online for free.

Like on this website: http://wordlist.sourceforge.net/

Just put it in a text file, and compare words with what is on the list. It should be order n with n being the number of words in the list. Do you need the time complexity faster?

Hope this helps.

Title: Efficient Dictionary lookup


问:
Can't instantiate javax.servlet.ServletException
I am trying to create instance of class javax.servlet.ServletException with following code

```<code>public class MyTroubleViewer {
 public static void main(String[] args) {
  javax.servlet.ServletException servletException = new javax.servlet.ServletException("Hello");
  System.out.println(servletException.getMessage());
 }
}
</code>```

But I get exception on creating:

```<code>Exception in thread "main" java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/servlet/ServletException
...
</code>```

Maven helps me with dependecies:

```<code><dependency>
 <groupId>javax</groupId>
 <artifactId>javaee-api</artifactId>
 <version>6.0</version>
 <type>jar</type>
 <scope>compile</scope>
</dependency>
</code>```

What am I doing wrong?

答:
ensure
1. servlet class is declared as public.
2. the path is correctly specified in web.xml or otherwise use annotations.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am trying to create instance of class javax.servlet.ServletException with following code

public class MyTroubleViewer {
 public static void main(String[] args) {
  javax.servlet.ServletException servletException = new javax.servlet.ServletException("Hello");
  System.out.println(servletException.getMessage());
 }
}

But I get exception on creating:

Exception in thread "main" java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/servlet/ServletException
...

Maven helps me with dependecies:

<dependency>
 <groupId>javax</groupId>
 <artifactId>javaee-api</artifactId>
 <version>6.0</version>
 <type>jar</type>
 <scope>compile</scope>
</dependency>

What am I doing wrong?


问:
To get historical data of memory consumption by a particular process before it gets stopped
I have a process (it is a windows service). It throws bad_alloc exception and stops. Later it is being started by another monitoring tool. I want to see the memory related details specific to that process just before it stops.

The tools like Process explorer, VMmap can be used for running processes. But, as my process stops we loose the data here. Is there any way to log the data of this process till it stops/ till some time period?

I tried 2 options in VMmap for the same.

(a) View Running process option works fine, but it needs regular 'Refresh' from user and During refresh if the process is stopped/restarted (now it is with new PID) the previous data are lost.

(b) Launch and trace a new process(here I have option of auto refresh after each second) -But it is not able to initiate my windows service.

Could you please suggest if there are any other ways for it?

I referred multiple articles for this , but none of them helped in my case.

The reason to capture logs is- these services are in production system on customer machines, so cannot analyse at the time of issue.

答: I am using Performance Monitor (PerfMon) to capture data specific to my process for every 10 minutes. It gives me both historic data as well as the current data.</p>


问:
Minimum number of steps to convert one integer to another
Recently i came across a problem, given 2 integers A and B, we need to convert A to B in minimum number of steps.
We can perform following operations on A:

If A is odd, decrease by 1

If A is even, increase by 1

Multiply A(even or odd) by 2

if A is even, divide by 2

again, we have to find the minimum number of steps needed to convert A to B.

The constraints are 0 < A, B < 10^18

My approach:
I tried to solve the problem using Breadth First Search, adding all the possible reachable numbers from a step into a queue, but it fails on higher constraints i.e. time outs.

Can anyone suggest a faster alternative?

EDIT: A is not necessarily less than B

答:
This problem can be optimised using dynamic programming.

I wrote the following code taking few things into consideration:

The infinite recursion should be avoided carefully by putting up base conditions. For eg: if A=0 and B<0, then no answer exists.

If the function convert(A, B) is called for more than 1 times into recursion and answer for the state (A, B) is not previously calculated, then recursion is terminated as no answer exists for this case. For eg: (80, 100) -> (160, 100) -> (80->100) -> (160, 100) -> ........

This is done by maintaining the count of each state into a map and defining the maximum recursive calls limit (3 in the following program) for the same state of DP.

The map dp maintains the answer for each state (A, B) and the map iterationsCount maintains the count of number of times the same state (A, B) is called.

Have a look at the following implementation:

```<code>#include <utility>
#include <iterator>
#include <map>
#include <set>
#include <iostream>
#include <climits>

typedef long long int LL;

std::map<std::pair<LL, LL>, LL> dp;

std::map<std::pair<LL, LL>, int > iterationsCount;

LL IMPOSSIBLE = (LL)1e9;

LL MAX_RECURSION_LIMIT = 3;

LL convert(LL a, LL b)
{
//std::cout<<a<<" "<<b<<std::endl;

    // To avoid infinite recursion:
        if(iterationsCount.find(std::make_pair(a, b))!=iterationsCount.end() &&
        iterationsCount[std::make_pair(a,b)] > MAX_RECURSION_LIMIT &&
        dp.find(std::make_pair(a,b))==dp.end()){
            return IMPOSSIBLE;
        }

    // Maintaining count of each state(A, B)
        iterationsCount[std::make_pair(a, b)]++;

    LL value1, value2, value3, value4, value5;

    value1 = value2 = value3 = value4 = value5 = IMPOSSIBLE;

    if(dp.find(std::make_pair(a,b)) != dp.end()){
        return dp[std::make_pair(a, b)];
    }

    // Base Case
    if(a==0 && b<0){
        return IMPOSSIBLE;
    }

    // Base Case
    if (a == b)
        return 0;

    //Conditions
    if (a%2 == 1){

        if(a < b){

            value1 = 1 + convert(2*a, b);

        }

        else if(a > b){

            value2 = 1 + convert(a-1, b);

        }
    }
    else{

        if(a < b){

            value3 = 1 + convert(a*2, b);

            value4 = 1 + convert(a+1, b);

        }

        else if(a > b){

            value5 = 1 + convert(a/2, b);

        }
    }

    LL ans = std::min(value1, std::min(value2, std::min(value3, std::min(value4, value5))));

    dp[std::make_pair(a, b)] = ans;

    return ans;
}

int main(){

    LL ans = convert(10, 95);
    if(ans == IMPOSSIBLE){
        std::cout<<"Impossible";
    }else{
        std::cout<<ans;
    }
    return 0;
}
</code>```

Body:
This problem can be optimised using dynamic programming.

I wrote the following code taking few things into consideration:

The infinite recursion should be avoided carefully by putting up base conditions. For eg: if A=0 and B<0, then no answer exists.

If the function convert(A, B) is called for more than 1 times into recursion and answer for the state (A, B) is not previously calculated, then recursion is terminated as no answer exists for this case. For eg: (80, 100) -> (160, 100) -> (80->100) -> (160, 100) -> ........

This is done by maintaining the count of each state into a map and defining the maximum recursive calls limit (3 in the following program) for the same state of DP.

The map dp maintains the answer for each state (A, B) and the map iterationsCount maintains the count of number of times the same state (A, B) is called.

Have a look at the following implementation:

#include <utility>
#include <iterator>
#include <map>
#include <set>
#include <iostream>
#include <climits>

typedef long long int LL;

std::map<std::pair<LL, LL>, LL> dp;

std::map<std::pair<LL, LL>, int > iterationsCount;

LL IMPOSSIBLE = (LL)1e9;

LL MAX_RECURSION_LIMIT = 3;

LL convert(LL a, LL b)
{
//std::cout<<a<<" "<<b<<std::endl;

    // To avoid infinite recursion:
        if(iterationsCount.find(std::make_pair(a, b))!=iterationsCount.end() &&
        iterationsCount[std::make_pair(a,b)] > MAX_RECURSION_LIMIT &&
        dp.find(std::make_pair(a,b))==dp.end()){
            return IMPOSSIBLE;
        }

    // Maintaining count of each state(A, B)
        iterationsCount[std::make_pair(a, b)]++;

    LL value1, value2, value3, value4, value5;

    value1 = value2 = value3 = value4 = value5 = IMPOSSIBLE;

    if(dp.find(std::make_pair(a,b)) != dp.end()){
        return dp[std::make_pair(a, b)];
    }

    // Base Case
    if(a==0 && b<0){
        return IMPOSSIBLE;
    }

    // Base Case
    if (a == b)
        return 0;

    //Conditions
    if (a%2 == 1){

        if(a < b){

            value1 = 1 + convert(2*a, b);

        }

        else if(a > b){

            value2 = 1 + convert(a-1, b);

        }
    }
    else{

        if(a < b){

            value3 = 1 + convert(a*2, b);

            value4 = 1 + convert(a+1, b);

        }

        else if(a > b){

            value5 = 1 + convert(a/2, b);

        }
    }

    LL ans = std::min(value1, std::min(value2, std::min(value3, std::min(value4, value5))));

    dp[std::make_pair(a, b)] = ans;

    return ans;
}

int main(){

    LL ans = convert(10, 95);
    if(ans == IMPOSSIBLE){
        std::cout<<"Impossible";
    }else{
        std::cout<<ans;
    }
    return 0;
}


问:
How to save multiple images to targeted folder in Opencv Python
I'm working in a project for Image Processing, I have already created the code for cropping and resizing it, however I didn't know how to save the multiple images into targeted folder.

Here is my code

```<code>from os import listdir
from os.path import isfile, join
import numpy
import cv2

filepath = 'DataMentah/akMundur'
onlyfiles = [f for f in listdir(filepath) if isfile(join(filepath))]
images = numpy.empty(len(onlyfiles), dtype = object)
for n in range(0, len(onlyfiles)):
    images[n] = cv2.imread(join(filepath, onlyfiles[n]))
    crp_img = images[0:240, 0:80]
    h = 224
    w = 224
    dimension = (h, w)
    rsz_image = cv2.resize(crp_img, dimension, interpolation = CV2.INTER_AREA)
    #saveimage to targeted folder
</code>```

答:
You simply write the images and make the number of your loop part of the name:

```<code>for n in range(0, len(onlyfiles)):
    # other things you need to do snipped
    cv2.imwrite(f'/path/to/destination/image_{n}.png',image)
</code>```

that way you get ordered names for it. You can use mini format language to format n like so:

```<code>for n in range(5):
    print(f"filename_{n:04}.png")   # format as 4 digits with leading zeros
</code>```

Output:

```<code>filename_0000.png
filename_0001.png
filename_0002.png
filename_0003.png
filename_0004.png
</code>```

See string format mini language for more formatting options.

Body:
I'm working in a project for Image Processing, I have already created the code for cropping and resizing it, however I didn't know how to save the multiple images into targeted folder.

Here is my code

from os import listdir
from os.path import isfile, join
import numpy
import cv2

filepath = 'DataMentah/akMundur'
onlyfiles = [f for f in listdir(filepath) if isfile(join(filepath))]
images = numpy.empty(len(onlyfiles), dtype = object)
for n in range(0, len(onlyfiles)):
    images[n] = cv2.imread(join(filepath, onlyfiles[n]))
    crp_img = images[0:240, 0:80]
    h = 224
    w = 224
    dimension = (h, w)
    rsz_image = cv2.resize(crp_img, dimension, interpolation = CV2.INTER_AREA)
    #saveimage to targeted folder

Body:
You simply write the images and make the number of your loop part of the name:

for n in range(0, len(onlyfiles)):
    # other things you need to do snipped
    cv2.imwrite(f'/path/to/destination/image_{n}.png',image)

that way you get ordered names for it. You can use mini format language to format n like so:

for n in range(5):
    print(f"filename_{n:04}.png")   # format as 4 digits with leading zeros

Output:

filename_0000.png
filename_0001.png
filename_0002.png
filename_0003.png
filename_0004.png

See string format mini language for more formatting options.


问:
Angular two way data binding with banana box syntax not working
I'm trying to do a two way data binding so that a property (file) in the parent can be updated by the child, whenever the child changes it.

The value in the parent is only ever undefined. What am I doing wrong?

In the child component (<cb-drag-and-drop-file>):

```<code>@Output() public fileChange = new EventEmitter<File>();
private fileValue: File;

@Input()
get file() {
    return this.fileValue;
}

set file(value) {
    this.fileValue = value;
}

private setDocument(uploadedFile: File): void {
    if (this.isFilesizeValid && this.isFileExtensionValid) {
        this.file = uploadedFile;
        this.fileChange.emit(uploadedFile);
        this.isFileValidAndUploaded = true;
    }
}

private clearOldFileReference(): void {
    this.file = undefined;
    this.fileChange.emit(undefined);
}
</code>```

In the parent component ts file:

```<code>file;
ngOnInit() {
   interval(1000).pipe(mapTo(this.file), tap(x => console.log(x))).subscribe(console.log);
}
</code>```

In the parent component html file:

```<code><cb-drag-and-drop-file fxFlex
                       [allowedFileTypes]="[FILE_TYPE_ENUM.Xlsx]"
                       [(file)]="file"
                       description="faslkdfjlsdkjf">
</cb-drag-and-drop-file>
</code>```

Surely I don't have to imperatively set file in the parent, that doesn't seem reactive which is what I thought Angular was going for with the event emitter? It would also mean I can't use banana box syntax wouldn't it? I've added fileChange to the parent and it is never fired when I use banana box syntax.

答:
Template with "banana in a box" notation ("Das Runde muss ins Eckige"):

```<code><your-comp [(file)]="file" ...
</code>```

YourCompComponent:

```<code>@Input('file')
file: string;

@Output('fileChange')
fileChanges$ = new EventEmitter();
...
this.fileChanges$.next('whatever');
</code>```

alternate:

```<code>private readonly bhs: BehaviorSubject<string> = new BehaviorSubject<string>('');

@Input('file')
file: string;

@Output('fileChange')
fileChanges$ = this.bhs.asObservable();
...
this.fileChanges$.next('whatever');
</code>```

Body:
I'm trying to do a two way data binding so that a property (file) in the parent can be updated by the child, whenever the child changes it.

The value in the parent is only ever undefined. What am I doing wrong?

In the child component (<cb-drag-and-drop-file>):

@Output() public fileChange = new EventEmitter<File>();
private fileValue: File;

@Input()
get file() {
    return this.fileValue;
}

set file(value) {
    this.fileValue = value;
}

private setDocument(uploadedFile: File): void {
    if (this.isFilesizeValid && this.isFileExtensionValid) {
        this.file = uploadedFile;
        this.fileChange.emit(uploadedFile);
        this.isFileValidAndUploaded = true;
    }
}

private clearOldFileReference(): void {
    this.file = undefined;
    this.fileChange.emit(undefined);
}

In the parent component ts file:

file;
ngOnInit() {
   interval(1000).pipe(mapTo(this.file), tap(x => console.log(x))).subscribe(console.log);
}

In the parent component html file:

<cb-drag-and-drop-file fxFlex
                       [allowedFileTypes]="[FILE_TYPE_ENUM.Xlsx]"
                       [(file)]="file"
                       description="faslkdfjlsdkjf">
</cb-drag-and-drop-file>

Surely I don't have to imperatively set file in the parent, that doesn't seem reactive which is what I thought Angular was going for with the event emitter? It would also mean I can't use banana box syntax wouldn't it? I've added fileChange to the parent and it is never fired when I use banana box syntax.

Body:
Template with "banana in a box" notation ("Das Runde muss ins Eckige"):

<your-comp [(file)]="file" ...

YourCompComponent:

@Input('file')
file: string;

@Output('fileChange')
fileChanges$ = new EventEmitter();
...
this.fileChanges$.next('whatever');

alternate:

private readonly bhs: BehaviorSubject<string> = new BehaviorSubject<string>('');

@Input('file')
file: string;

@Output('fileChange')
fileChanges$ = this.bhs.asObservable();
...
this.fileChanges$.next('whatever');


问:
How to calculate 3D histogram in python using open CV
I want to calculate 3D histogram of my Cielab image in python. I am using openCV to calculate my histogram. I want to compare images using compareHist function of openCV, thats why I am using openCV to compute 3D histogram of my image.

I tried with the following variables:

```<code>i_lab = image.copy()
i_lab = i_lab.astype(np.uint8)
Range_hist = [[0, 100], [-100, 100], [-100, 100]]
hist_1 = cv2.calcHist([i_lab], [[0], [1], [2]], None, [[20], [20], [20]], Range_hist)
</code>```

But it gives error SystemError: error return without exception set
Please tell me what am I doing wrong and if it is possible to compute 3D histogram using openCV in python

答:
For computing a histogram in cielab, this worked for me:

function signature of calcHist: images, channels, mask, number of bins, array of the dims arrays of the histogram bin boundaries in each dimension.

```<code>img = cv2.imread(file) # in bgr
hist = cv2.calcHist([img],[0, 1, 2],None,[256, 256, 256],[0, 255, 0, 255, 0, 255]) # in bgr
img = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) # in lab
hist = cv2.calcHist([img],[0, 1, 2],None,[100, 2*128, 2*128],[0, 100, -128, 127, -128, 127])`# in lab

correlation = cv2.HISTCMP_CORREL # compare histograms using correlation
corr = cv2.compareHist(img, img2, correlation)
</code>```

Body:
I want to calculate 3D histogram of my Cielab image in python. I am using openCV to calculate my histogram. I want to compare images using compareHist function of openCV, thats why I am using openCV to compute 3D histogram of my image.

I tried with the following variables:

i_lab = image.copy()
i_lab = i_lab.astype(np.uint8)
Range_hist = [[0, 100], [-100, 100], [-100, 100]]
hist_1 = cv2.calcHist([i_lab], [[0], [1], [2]], None, [[20], [20], [20]], Range_hist)

But it gives error SystemError: error return without exception set
Please tell me what am I doing wrong and if it is possible to compute 3D histogram using openCV in python

Body:
For computing a histogram in cielab, this worked for me:

function signature of calcHist: images, channels, mask, number of bins, array of the dims arrays of the histogram bin boundaries in each dimension.

img = cv2.imread(file) # in bgr
hist = cv2.calcHist([img],[0, 1, 2],None,[256, 256, 256],[0, 255, 0, 255, 0, 255]) # in bgr
img = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) # in lab
hist = cv2.calcHist([img],[0, 1, 2],None,[100, 2*128, 2*128],[0, 100, -128, 127, -128, 127])`# in lab

correlation = cv2.HISTCMP_CORREL # compare histograms using correlation
corr = cv2.compareHist(img, img2, correlation)


问:
How to get data in Angular 8 when only we have one object to be received
The error I get:

core.js:6260 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

at NgForOf.ngDoCheck (common.js:4406)

  at callHook (core.js:4762)

  at callHooks (core.js:4722)

  at executeCheckHooks (core.js:4642)

  at refreshView (core.js:11979)

  at refreshComponent (core.js:13449)

  at refreshChildComponents (core.js:11689)

  at refreshView (core.js:12024)

  at refreshComponent (core.js:13449)

  at refreshChildComponents (core.js:11689)

The code below works if I have more then one object. When the data is as shown below, and from that, I understand that something is wrong with array or object but I am unable to figure it out. So when I have 2 objects I get the data in the dropdown, but when it is one I get the error mentioned above.

```<code>[
{..},
{..}
]
</code>```

My data Looks like this:

```<code>{
"details_id": 218,
"master_code": 218,
"MstCode": null,
"start_date": "2020-02-29T00:00:00",
"end_date": "2020-02-29T00:00:00",
"canceled": "False   ",
"data_archived": null,
"last_updated_on": "2020-02-28 11:37:08",
"last_updated_by": null
}
</code>```

My http get request code is as below:

```<code>this.http.get(this.apiBaseUrl+"ProgramDets/"+id).toPromise().then(res => this.Details = res as TrDetails);
</code>```

My model code:

```<code>export class TrDetails {
    details_id: number;
    master_code: number;
    MstCode: number;
    start_date: Date;
    end_date: Date;
    canceled: string;
    data_archived: string;
    last_updated_on: Date;
    last_updated_by: string;
}
</code>```

My service code:

```<code>apiBaseUrl = "http://localhost:2676/api/";
Details : TrainingDetails;

GetDetails(id){
    this.http.get(this.apiBaseUrl+"ProgramDets/"+id).toPromise().then(res =>
    this.Details = res as TrDetails);
  }
</code>```

My dropdown code:

```<code><option *ngFor="let data of service.Details" [value]="data.start_date">{{data.program_start_date}}</option>
</code>```

答:
If your logic is working when the response is an array, you just need to add any object response to an empty array before using it. Try changing your GetDetails method body to below</p>

```<code>this.http.get(this.apiBaseUrl+"ProgramDets/"+id).toPromise().then((res: TrDetails | TrDetails[]) => this.Details = Array.isArray(res) ? res : [res]);
</code>```

Body:
The error I get:

core.js:6260 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

at NgForOf.ngDoCheck (common.js:4406)

  at callHook (core.js:4762)

  at callHooks (core.js:4722)

  at executeCheckHooks (core.js:4642)

  at refreshView (core.js:11979)

  at refreshComponent (core.js:13449)

  at refreshChildComponents (core.js:11689)

  at refreshView (core.js:12024)

  at refreshComponent (core.js:13449)

  at refreshChildComponents (core.js:11689)

The code below works if I have more then one object. When the data is as shown below, and from that, I understand that something is wrong with array or object but I am unable to figure it out. So when I have 2 objects I get the data in the dropdown, but when it is one I get the error mentioned above.

[
{..},
{..}
]

My data Looks like this:

{
"details_id": 218,
"master_code": 218,
"MstCode": null,
"start_date": "2020-02-29T00:00:00",
"end_date": "2020-02-29T00:00:00",
"canceled": "False   ",
"data_archived": null,
"last_updated_on": "2020-02-28 11:37:08",
"last_updated_by": null
}

My http get request code is as below:

this.http.get(this.apiBaseUrl+"ProgramDets/"+id).toPromise().then(res => this.Details = res as TrDetails);

My model code:

export class TrDetails {
    details_id: number;
    master_code: number;
    MstCode: number;
    start_date: Date;
    end_date: Date;
    canceled: string;
    data_archived: string;
    last_updated_on: Date;
    last_updated_by: string;
}

My service code:

apiBaseUrl = "http://localhost:2676/api/";
Details : TrainingDetails;

GetDetails(id){
    this.http.get(this.apiBaseUrl+"ProgramDets/"+id).toPromise().then(res =>
    this.Details = res as TrDetails);
  }

My dropdown code:

<option *ngFor="let data of service.Details" [value]="data.start_date">{{data.program_start_date}}</option>

Body:
If your logic is working when the response is an array, you just need to add any object response to an empty array before using it. Try changing your GetDetails method body to below

this.http.get(this.apiBaseUrl+"ProgramDets/"+id).toPromise().then((res: TrDetails | TrDetails[]) => this.Details = Array.isArray(res) ? res : [res]);


问:
How to use ng-style with !important?
Tag Button already has cursor css assigned. I want to override cursor css according to is_active values to disable button.
is_active may have values 0 or 1. Following is code for js/html please let me know correct method to apply cursor css to button.

$scope.ngStyleDisabled = function(status) {
  if (status == 1) {
    return {};
  } else if (status == 0) {
    return '{\'cursor\':\'not-allowed !important\',\'pointer-events\':\'none\'}';
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<button ng-style="{{ngStyleDisabled(item.is_active)}}">Action Button</button></code>```

答:
Spoiler alert: everyone who said ng-style does not support !important is *WRONG!!

*Well, sort of wrong.  I.e. while it definitely isn't supported out of the box, you can force it with the following workaround (simplified here for convenience):

```<code><elem data-ng-attr-style="{{ 'color: ' + your_color_var + ' !important' }}"></elem>
</code>```

e.g.

```<code><span data-ng-attr-style="{{ 'color: indigo !important' }}"></span>
</code>```

Wait... so we have to use a hack to get !important working!?!  That's like... a double
  hack!!!  Or   a double double cross!!  A triple cross?!?

Lol.

Title: How to use ng-style with !important?

Body:
Tag Button already has cursor css assigned. I want to override cursor css according to is_active values to disable button.
is_active may have values 0 or 1. Following is code for js/html please let me know correct method to apply cursor css to button.

$scope.ngStyleDisabled = function(status) {
  if (status == 1) {
    return {};
  } else if (status == 0) {
    return '{\'cursor\':\'not-allowed !important\',\'pointer-events\':\'none\'}';
  }
}

<button ng-style="{{ngStyleDisabled(item.is_active)}}">Action Button</button>

Body:
Spoiler alert: everyone who said ng-style does not support !important is *WRONG!!

*Well, sort of wrong.  I.e. while it definitely isn't supported out of the box, you can force it with the following workaround (simplified here for convenience):

<elem data-ng-attr-style="{{ 'color: ' + your_color_var + ' !important' }}"></elem>

e.g.

<span data-ng-attr-style="{{ 'color: indigo !important' }}"></span>

Wait... so we have to use a hack to get !important working!?!  That's like... a double
  hack!!!  Or   a double double cross!!  A triple cross?!?

Lol.


问:
Find elements with class "x", ignore elements with "x" and more classes
I have HTML that looks something like this:

```<code><span class="x">Text 1</span>
<span class="x y">Text 2</span>
<span class="x">Text 3</span>
<span class="x z">Text 4</span>
</code>```

I can use this to find all children with the class x:

```<code>for span_text in soup_subset.findChildren('span', class_='x'):
    print (span_text)
</code>```

This will output text of span elements with just the x class, as well as those with x and another class.

How do I find children with just the x class, ignoring those that have x and some other class?

答:
Use  a CSS selector to get span tags with only that class.

```<code>soup.select("span[class='x']")
</code>```

Code

```<code>from bs4 import BeautifulSoup
html ="""
<span class="x">Text 1</span>
<div class="x">Div Text 1</div>
<span class="x y">Text 2</span>
<span class="x">Text 3</span>
<span class="x z">Text 4</span>
"""
soup = BeautifulSoup(html, 'html.parser')
print(soup.select("span[class='x']"))
</code>```

Output

```<code>[<span class="x">Text 1</span>, <span class="x">Text 3</span>]
</code>```

Ref

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors

Body:
I have HTML that looks something like this:

Text 1
Text 2
Text 3
Text 4

I can use this to find all children with the class x:

for span_text in soup_subset.findChildren('span', class_='x'):
    print (span_text)

This will output text of span elements with just the x class, as well as those with x and another class.

How do I find children with just the x class, ignoring those that have x and some other class?

Body:
Use  a CSS selector to get span tags with only that class.

soup.select("span[class='x']")

Code

from bs4 import BeautifulSoup
html ="""
<span class="x">Text 1</span>
<div class="x">Div Text 1</div>
<span class="x y">Text 2</span>
<span class="x">Text 3</span>
<span class="x z">Text 4</span>
"""
soup = BeautifulSoup(html, 'html.parser')
print(soup.select("span[class='x']"))

Output

[<span class="x">Text 1</span>, <span class="x">Text 3</span>]

Ref

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors


问:
Updating label text in frame when job is finished
When pressing "Ping test" you get a new 'main window' with input and submit button.
when Submit is clicked, a file is created on the desktop and writes the output result of ping command.
right now, when I enter an address and click submit, I only see the menu frame and the main frame, the output frame shows up when the proccess is finished.

how can I make the output frame show "Pinging..." when I click the Submit button and update the label to "Ping Complete!" when its finished?

here's my code:

```<code>import tkinter as tk
import subprocess as sub
import easygui
import os

root = tk.Tk()
root.geometry("400x300")

# ===== Frame 1 - Left Menu =====
frame = tk.LabelFrame(root, text="Menu",height=80, width=40,
                      padx=5, pady=5, relief="solid")
frame.place(x=10, y=0)

# Show files button
showfilesButton = tk.Button(frame, text="Show Files", padx=5, pady=5,
                            command=lambda: showFiles())
showfilesButton.grid(row=1, column=0)

# ConvertURL button
convertURL = tk.Button(frame, text="Ping Test", padx=5, pady=5,
                       command=lambda: testPing.getURL())
convertURL.grid(row=2, column=0)

# Quit Button
endProgram = tk.Button(frame, text="Quit", padx=5, pady=5,
                       command=lambda: terminate())
endProgram.grid(row=3, column=0)

class testPing():

    def __init__(self, host):
        self.host = host
        self.clearFile = clearFile
        self.label = label

    def getURL():

        frame2 = tk.LabelFrame(root, text="Main Window", height=350, width=300, padx=30, pady=30)
        frame2.pack()

        urlLabel = tk.Label(frame2, text="Enter URL : ", padx=5, pady=5)
        urlLabel.place(x=-30, y=-30)
        urlInputBox = tk.Entry(frame2)
        urlInputBox.pack()

        clearLabel = tk.Label(frame2, text="Clear File?", padx=5, pady=5)
        clearLabel.place(x=-30, y=20)

        clearFile = tk.BooleanVar()
        clearFile.set(False)
        clearFileRadioYes = tk.Radiobutton(frame2, text="yes", value=True, var=clearFile,
                                           command=lambda: testPing.callback(clearFile.get()))
        clearFileRadioYes.place(x=-30, y=45)

        clearFileRadioNo = tk.Radiobutton(frame2, text="no", value=False, var=clearFile,
                                          command=lambda: testPing.callback(clearFile.get()))
        clearFileRadioNo.place(x=20, y=45)

        urlSubmitButton = tk.Button(frame2, text="Submit",
                                    command=lambda: testPing.pingURL(urlInputBox.get(), clearFile.get()))
        urlSubmitButton.pack(side=tk.RIGHT)

    def callback(clearFile):

        bul = clearFile
        print(bul)

    def pingURL(host, clearFile):

        outputLabel = tk.LabelFrame(root, text="Output", height=35, width=150,
                               padx=5, pady=5, relief="solid")
        outputLabel.place(x=0, y=150)
        file = fr'c:/users/{os.getlogin()}/Desktop/ping.txt'
        label = tk.Label(outputLabel, text=f'Pinging {host} ...')
        label.grid(row=0, column=0)

        clear = clearFile

        if clear == True:
            with open(file, 'w+') as output:
                output.truncate(0)
                sub.call(['ping', f'{host}'], stdout=output)

        else:
            with open(file, 'a') as output:
                sub.call(['ping', f'{host}'], stdout=output)

        output.close()
        # testPing.changeLabel(host)

    def changeLabel(host):

        myLabel = tk.Label.config(text=f"Ping to {host} Complete!")
        myLabel.pack()

def terminate():
    exit()

def showFiles():

    path = easygui.diropenbox()  # Opens a folder dialog box.
    folder = path
    filelocation = f"c:\\Users\\{os.getlogin()}\\Desktop\\showFilesResult.txt"
    filenames = os.listdir(folder)  # Get the file names in the folder.

    # Writing to file
    with open(filelocation, 'a') as file:
        for name in filenames:
            file.write(f"Name: {name}\nFolder Path: {folder}\n!------------------------------!\n")

    print("Done!")

root.mainloop()
</code>```

答:
Instead of calling changeLabel(), you can simply put:

```<code>output.close()
label.configure(text=f'Ping to {host} complete!')
# testPing.changeLabel(host)
</code>```

But remember about updating your label first, if you don't at the end only complete label will be visible.

```<code>label = tk.Label(outputLabel, text=f'Pinging {host} ...')
label.grid(row=0, column=0)
label.update()
</code>```

An additional tip, don't use different GUI creators in one project. If you only using easygui to get the path, check Tkinter methods -> askopenfilename and asksaveasfilename.

Body:
When pressing "Ping test" you get a new 'main window' with input and submit button.
when Submit is clicked, a file is created on the desktop and writes the output result of ping command.
right now, when I enter an address and click submit, I only see the menu frame and the main frame, the output frame shows up when the proccess is finished.

how can I make the output frame show "Pinging..." when I click the Submit button and update the label to "Ping Complete!" when its finished?

here's my code:

import tkinter as tk
import subprocess as sub
import easygui
import os

root = tk.Tk()
root.geometry("400x300")

# ===== Frame 1 - Left Menu =====
frame = tk.LabelFrame(root, text="Menu",height=80, width=40,
                      padx=5, pady=5, relief="solid")
frame.place(x=10, y=0)

# Show files button
showfilesButton = tk.Button(frame, text="Show Files", padx=5, pady=5,
                            command=lambda: showFiles())
showfilesButton.grid(row=1, column=0)

# ConvertURL button
convertURL = tk.Button(frame, text="Ping Test", padx=5, pady=5,
                       command=lambda: testPing.getURL())
convertURL.grid(row=2, column=0)

# Quit Button
endProgram = tk.Button(frame, text="Quit", padx=5, pady=5,
                       command=lambda: terminate())
endProgram.grid(row=3, column=0)

class testPing():

    def __init__(self, host):
        self.host = host
        self.clearFile = clearFile
        self.label = label

    def getURL():

        frame2 = tk.LabelFrame(root, text="Main Window", height=350, width=300, padx=30, pady=30)
        frame2.pack()

        urlLabel = tk.Label(frame2, text="Enter URL : ", padx=5, pady=5)
        urlLabel.place(x=-30, y=-30)
        urlInputBox = tk.Entry(frame2)
        urlInputBox.pack()

        clearLabel = tk.Label(frame2, text="Clear File?", padx=5, pady=5)
        clearLabel.place(x=-30, y=20)

        clearFile = tk.BooleanVar()
        clearFile.set(False)
        clearFileRadioYes = tk.Radiobutton(frame2, text="yes", value=True, var=clearFile,
                                           command=lambda: testPing.callback(clearFile.get()))
        clearFileRadioYes.place(x=-30, y=45)

        clearFileRadioNo = tk.Radiobutton(frame2, text="no", value=False, var=clearFile,
                                          command=lambda: testPing.callback(clearFile.get()))
        clearFileRadioNo.place(x=20, y=45)

        urlSubmitButton = tk.Button(frame2, text="Submit",
                                    command=lambda: testPing.pingURL(urlInputBox.get(), clearFile.get()))
        urlSubmitButton.pack(side=tk.RIGHT)

    def callback(clearFile):

        bul = clearFile
        print(bul)

    def pingURL(host, clearFile):

        outputLabel = tk.LabelFrame(root, text="Output", height=35, width=150,
                               padx=5, pady=5, relief="solid")
        outputLabel.place(x=0, y=150)
        file = fr'c:/users/{os.getlogin()}/Desktop/ping.txt'
        label = tk.Label(outputLabel, text=f'Pinging {host} ...')
        label.grid(row=0, column=0)

        clear = clearFile

        if clear == True:
            with open(file, 'w+') as output:
                output.truncate(0)
                sub.call(['ping', f'{host}'], stdout=output)

        else:
            with open(file, 'a') as output:
                sub.call(['ping', f'{host}'], stdout=output)

        output.close()
        # testPing.changeLabel(host)

    def changeLabel(host):

        myLabel = tk.Label.config(text=f"Ping to {host} Complete!")
        myLabel.pack()

def terminate():
    exit()

def showFiles():

    path = easygui.diropenbox()  # Opens a folder dialog box.
    folder = path
    filelocation = f"c:\\Users\\{os.getlogin()}\\Desktop\\showFilesResult.txt"
    filenames = os.listdir(folder)  # Get the file names in the folder.

    # Writing to file
    with open(filelocation, 'a') as file:
        for name in filenames:
            file.write(f"Name: {name}\nFolder Path: {folder}\n!------------------------------!\n")

    print("Done!")

root.mainloop()

Body:
Instead of calling changeLabel(), you can simply put:

output.close()
label.configure(text=f'Ping to {host} complete!')
# testPing.changeLabel(host)

But remember about updating your label first, if you don't at the end only complete label will be visible.

label = tk.Label(outputLabel, text=f'Pinging {host} ...')
label.grid(row=0, column=0)
label.update()

An additional tip, don't use different GUI creators in one project. If you only using easygui to get the path, check Tkinter methods -> askopenfilename and asksaveasfilename.


问:
How to shift my code in other block in Java?
When I run the whole program, the code always repeats in login activity and shows You do not have the account message in the loop. How do I move to createNewUser? I have attached the image of the code.
https://i.stack.imgur.com/DIqNp.png</p>

答:
you can call the desired method wherever you want and if it of another class then you need to create an object and then call the method, and if it is a static method then you can call it by class name only.

so here if the user is null then you need to call the CreateNewUser method.


问:
Github Actions - Is there a way to continue on error while still getting correct feedback?
I'm new to Github Actions, and I'm trying to find a way to achieve the following functionality:
Whenever a step fails, it will show that it failed (will provide correct feedback) but will still continue to other steps.

At the moment, failure causes the step to stop:

I've seen the most popular suggestion is to use continue-on-error, but that seems to make the step's conclusion 'Success', and will not show it failed unless you go into the logs.

In the screenshot above, the "Secrets" step failed, and yet it appears to be successful unless entering the logs.

When reading this thread,  I came to suspect this feature might not exist yet in GH actions.

I've also tried using conditionals for each step, and/or for the job.
For example, I've tried:
if: ${{ success() }} || ${{ failure() }} - this simply did not provide the needed functionality, the step failed and the next step did not start.

if: succeeded() || failed() - took this syntax from the Github community thread above, but it generated a syntax error (which makes sense, since it isn't compatible with the syntax specified here).

To conclude, I'm looking for a way to make steps that fail indicate they failed, and still make the workflow continue to the next step.

Thank you!

答:
To my surprise, and thanks to @smac89 for suggesting it - adding if: always() seems to do the trick.
I'm still wondering why if: ${{ success() }} || ${{ failure() }} failed, but the solution seems to work for the moment.
Thank you for the help!


问:
How do I fill each data set as a different color?
If you execute the code the colors are all black. I need to change it to different colors but I can't seem to get it to work. I've tried finding a solution online but it didn't help much.

Load r packages

```<code>
library(ggplot2) #Import package for more customizable plots
library(reshape2) #Import package to melt dataframe

</code>```

Sample data

```<code>
#Determining how many bags of cat nip to buy for an dog animal show using the hypergeometric distribution.

populationSize = 1000 #Population of animals in a given city (Population Size)
numberOfCatsInTown = c(50, 150, 300) #Number of Cats in the town
numberOfAnimalsAtEvent = 250 #How many animals show up to the event (Sample Size)
x = seq(0, 80) #Probability of getting x number of cats attending the event

# Calculate Probabilities for the PMF

scenario1d = dhyper(x, numberOfCatsInTown[1], populationSize, numberOfAnimalsAtEvent) #hypergeometric PMF
scenario2d = dhyper(x, numberOfCatsInTown[2], populationSize, numberOfAnimalsAtEvent) #hypergeometric PMF
scenario3d = dhyper(x, numberOfCatsInTown[3], populationSize, numberOfAnimalsAtEvent) #hypergeometric PMF

# Calcualte the Probabilities for the CDF

scenario1p = phyper(x, numberOfCatsInTown[1], populationSize, numberOfAnimalsAtEvent) #hypergeometric CDF
scenario2p = phyper(x, numberOfCatsInTown[2], populationSize, numberOfAnimalsAtEvent) #hypergeometric CDF
scenario3p = phyper(x, numberOfCatsInTown[3], populationSize, numberOfAnimalsAtEvent) #hypergeometric CDF

#Create dataframes

myDataFrame = data.frame(x, scenario1d, scenario2d, scenario3d) #Creates a dataframe for the PMF
myDataFrame2 = data.frame(x, scenario1p, scenario2p, scenario3p) #Creates a dataframe for the CDF

#Melt the dataframes

data.m1 = melt(myDataFrame, id.vars = "x")
data.m2 = melt(myDataFrame2, id.vars = "x")

</code>```

Plots

```<code>
#Create a plot for the PMF

ggplot(data.m1, aes(x = x, y = value, fill = variable)) +
      geom_point() + geom_line() +
      labs(x = "x", y = "Probability", title = "PMF Number of Cats at the Animal Show (N = 1000, n = 250)") +
      theme(plot.title = element_text(hjust = 0.5), legend.position = c(0.9,0.8)) +
      scale_fill_discrete(name = "M", labels = c("50", "150", "300")) +

#Create a plot for the CDF

ggplot(data.m2, aes(x = x, y = value, fill = variable)) +
      geom_point() + geom_line() +
      labs(x = "x", y = "Probability", title = "CDF Number of Cats at the Animal Show (N = 1000, n = 250)") +
      theme(plot.title = element_text(hjust = 0.5), legend.position = c(0.9, 0.2)) +
      scale_color_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"))

</code>```

Any help would be appreciated, thanks.

答:
You need to change fill to color in ggplots aes() call:

```<code>library(ggplot2)
ggplot(data.m1, aes(x = x, y = value, color = variable)) +
  geom_point() + geom_line() +
  labs(x = "x", y = "Probability", title = "PMF Number of Cats at the Animal Show (N = 1000, n = 250)") +
  theme(plot.title = element_text(hjust = 0.5), legend.position = c(0.9,0.8)) +
  scale_color_discrete(name = "M", labels = c("50", "150", "300"))

  #Create a plot for the CDF

  ggplot(data.m2, aes(x = x, y = value, color = variable)) +
  geom_point() + geom_line() +
  labs(x = "x", y = "Probability", title = "CDF Number of Cats at the Animal Show (N = 1000, n = 250)") +
  theme(plot.title = element_text(hjust = 0.5), legend.position = c(0.9, 0.2)) +
  scale_color_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"), labels = c("50", "150", "300"))
</code>```

Body:
If you execute the code the colors are all black. I need to change it to different colors but I can't seem to get it to work. I've tried finding a solution online but it didn't help much.

Load r packages

library(ggplot2) #Import package for more customizable plots
library(reshape2) #Import package to melt dataframe

Sample data

#Determining how many bags of cat nip to buy for an dog animal show using the hypergeometric distribution.

populationSize = 1000 #Population of animals in a given city (Population Size)
numberOfCatsInTown = c(50, 150, 300) #Number of Cats in the town
numberOfAnimalsAtEvent = 250 #How many animals show up to the event (Sample Size)
x = seq(0, 80) #Probability of getting x number of cats attending the event

# Calculate Probabilities for the PMF

scenario1d = dhyper(x, numberOfCatsInTown[1], populationSize, numberOfAnimalsAtEvent) #hypergeometric PMF
scenario2d = dhyper(x, numberOfCatsInTown[2], populationSize, numberOfAnimalsAtEvent) #hypergeometric PMF
scenario3d = dhyper(x, numberOfCatsInTown[3], populationSize, numberOfAnimalsAtEvent) #hypergeometric PMF

# Calcualte the Probabilities for the CDF

scenario1p = phyper(x, numberOfCatsInTown[1], populationSize, numberOfAnimalsAtEvent) #hypergeometric CDF
scenario2p = phyper(x, numberOfCatsInTown[2], populationSize, numberOfAnimalsAtEvent) #hypergeometric CDF
scenario3p = phyper(x, numberOfCatsInTown[3], populationSize, numberOfAnimalsAtEvent) #hypergeometric CDF

#Create dataframes

myDataFrame = data.frame(x, scenario1d, scenario2d, scenario3d) #Creates a dataframe for the PMF
myDataFrame2 = data.frame(x, scenario1p, scenario2p, scenario3p) #Creates a dataframe for the CDF

#Melt the dataframes

data.m1 = melt(myDataFrame, id.vars = "x")
data.m2 = melt(myDataFrame2, id.vars = "x")

Plots

#Create a plot for the PMF

ggplot(data.m1, aes(x = x, y = value, fill = variable)) +
      geom_point() + geom_line() +
      labs(x = "x", y = "Probability", title = "PMF Number of Cats at the Animal Show (N = 1000, n = 250)") +
      theme(plot.title = element_text(hjust = 0.5), legend.position = c(0.9,0.8)) +
      scale_fill_discrete(name = "M", labels = c("50", "150", "300")) +

#Create a plot for the CDF

ggplot(data.m2, aes(x = x, y = value, fill = variable)) +
      geom_point() + geom_line() +
      labs(x = "x", y = "Probability", title = "CDF Number of Cats at the Animal Show (N = 1000, n = 250)") +
      theme(plot.title = element_text(hjust = 0.5), legend.position = c(0.9, 0.2)) +
      scale_color_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"))

Any help would be appreciated, thanks.

Body:
You need to change fill to color in ggplots aes() call:

library(ggplot2)
ggplot(data.m1, aes(x = x, y = value, color = variable)) +
  geom_point() + geom_line() +
  labs(x = "x", y = "Probability", title = "PMF Number of Cats at the Animal Show (N = 1000, n = 250)") +
  theme(plot.title = element_text(hjust = 0.5), legend.position = c(0.9,0.8)) +
  scale_color_discrete(name = "M", labels = c("50", "150", "300"))

  #Create a plot for the CDF

  ggplot(data.m2, aes(x = x, y = value, color = variable)) +
  geom_point() + geom_line() +
  labs(x = "x", y = "Probability", title = "CDF Number of Cats at the Animal Show (N = 1000, n = 250)") +
  theme(plot.title = element_text(hjust = 0.5), legend.position = c(0.9, 0.2)) +
  scale_color_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"), labels = c("50", "150", "300"))


问:
Xamarin - Android app cant access site anymore
I've made an app that calls a website to populate its content... it worked without problems, but suddenly today I noticed that the app is not getting data from the site anymore. On all installations of the app. How is this possible? Has my site been added to some sort of blacklist for whatever reason by google?

EDIT:

if I open Url in the browser i see "1".. but this returns "":

```<code>     downloadString = await client.DownloadStringTaskAsync(URL);
</code>```

also SSL checker on the URL reports a expired certificate, but the dates seem to be ok:

```<code>   Common name: gallery-share.com
SANs: gallery-share.com, autodiscover.gallery-share.com, cpanel.gallery-
share.com, cpcalendars.gallery-share.com, cpcontacts.gallery-share.com,
mail.gallery-share.com, webdisk.gallery-share.com, webmail.gallery-share.com,
whm.gallery-share.com, www.gallery-share.com
Valid from March 30, 2020 to June 29, 2020
Serial Number: 92d96e0255980f1ae39d34d0c11576ef
Signature Algorithm: sha256WithRSAEncryption
Issuer: cPanel, Inc. Certification Authority
</code>```

https://www.sslshopper.com/ssl-checker.html#hostname=gallery-share.com

答: The problem was that one of the ssl certificates was expired.. Renewing the certificate on the site sovled the problem.</p>

Body:
I've made an app that calls a website to populate its content... it worked without problems, but suddenly today I noticed that the app is not getting data from the site anymore. On all installations of the app. How is this possible? Has my site been added to some sort of blacklist for whatever reason by google?

EDIT:

if I open Url in the browser i see "1".. but this returns "":

     downloadString = await client.DownloadStringTaskAsync(URL);

also SSL checker on the URL reports a expired certificate, but the dates seem to be ok:

   Common name: gallery-share.com
SANs: gallery-share.com, autodiscover.gallery-share.com, cpanel.gallery-
share.com, cpcalendars.gallery-share.com, cpcontacts.gallery-share.com,
mail.gallery-share.com, webdisk.gallery-share.com, webmail.gallery-share.com,
whm.gallery-share.com, www.gallery-share.com
Valid from March 30, 2020 to June 29, 2020
Serial Number: 92d96e0255980f1ae39d34d0c11576ef
Signature Algorithm: sha256WithRSAEncryption
Issuer: cPanel, Inc. Certification Authority

https://www.sslshopper.com/ssl-checker.html#hostname=gallery-share.com