问:
Setting and checking null in Azure Pipeline YAML
I'm trying to add an option to one of our YAML pipelines that allows a user to set which parts of the project will and won't be deployed. To do this, I'm setting variables based on a user's checkbox selection like so:

```<code> variables:
    - template:         variables.yml
    - name: deliverStageOne
      ${{ if eq(parameters.DeliverStageOne, 'False') }}:
        value: ''
      ${{ if eq(parameters.DeliverStageOne, 'True') }}:
        value: 'STAGE_ONE'
</code>```

The next part of the process takes all these variables as an array called dbNames and uses a for loop to process each with the same block of code:

```<code>steps:
  - ${{ each dbName in parameters.dbNames }}:
    - ${{ if ne(dbName, '') }}:
      - powershell:               [powershell command]
</code>```

The trouble I'm having with this is that the conditional inside the above loop never seems to work - it always evaluates to True.

I've tried setting value to x and using

```<code>- ${{ if ne(dbName, 'x') }}:
</code>```

And that evaluates to true, even when I've checked the value of dbName with echo and confirmed that it is x.

So I figured that this was something to do with the way YAML handles strings, and since '' is clumsy syntax anyway, I thought it would be better and clearer to set it to null:

```<code>      ${{ if eq(parameters.DeliverStageOne, 'False') }}:
        value: null
</code>```

Using this in an ne expression results in a compile error:

```<code>- ${{ if ne(dbName, null) }}:
</code>```

And reading the documentation suggests I can just do:

```<code>- ${{ if dbName }}:
</code>```

However, while the above compiles, it continues to treat the null as though it's a string 'null' and falls into th powershell step beneath.

How can I set this up so that YAML recognises that I've created a null value, and checks for it successfully?

答:
For parameters, various data types are supported. See link.

But for variables, they are always of string data type, with or without quotes. In another words, '' is evaluated as an empty string, but not null. See link.

Since all variables are treated as strings in Azure Pipelines, an empty string is equivalent to null in this pipeline.

Instead, try to use this syntax to test if the variable is an empty string in your case:

- ${{ if eq(length(dbName), 0) }}:
```

Body:
I'm trying to add an option to one of our YAML pipelines that allows a user to set which parts of the project will and won't be deployed. To do this, I'm setting variables based on a user's checkbox selection like so:

 variables:
    - template:         variables.yml
    - name: deliverStageOne
      ${{ if eq(parameters.DeliverStageOne, 'False') }}:
        value: ''
      ${{ if eq(parameters.DeliverStageOne, 'True') }}:
        value: 'STAGE_ONE'

The next part of the process takes all these variables as an array called dbNames and uses a for loop to process each with the same block of code:

steps:
  - ${{ each dbName in parameters.dbNames }}:
    - ${{ if ne(dbName, '') }}:
      - powershell:               [powershell command]

The trouble I'm having with this is that the conditional inside the above loop never seems to work - it always evaluates to True.

I've tried setting value to x and using

- ${{ if ne(dbName, 'x') }}:

And that evaluates to true, even when I've checked the value of dbName with echo and confirmed that it is x.

So I figured that this was something to do with the way YAML handles strings, and since '' is clumsy syntax anyway, I thought it would be better and clearer to set it to null:

      ${{ if eq(parameters.DeliverStageOne, 'False') }}:
        value: null

Using this in an ne expression results in a compile error:

- ${{ if ne(dbName, null) }}:

And reading the documentation suggests I can just do:

- ${{ if dbName }}:

However, while the above compiles, it continues to treat the null as though it's a string 'null' and falls into th powershell step beneath.

How can I set this up so that YAML recognises that I've created a null value, and checks for it successfully?


来源: stackexchange

问:
configService.get() cannot read env variable from .env file in NestJS
I am trying to set TypeOrm configuration object using env variables in NestJS. The configuration object should read 'DB_NAME' env variable(set to db.sqlite) set in a .development.env file. The env variable is provided via configService.get('DB_NAME) api of @nestjs/config library. My code in app.module.ts files is as follows:

```<code>   import { ConfigModule, ConfigService } from '@nestjs/config';
    import { TypeOrmModule } from '@nestjs/typeorm';

    @Module({
      imports: [ConfigModule.forRoot({
        isGlobal: true,
        envFilePath: `.${process.env.NODE_ENV}.env`
      }), TypeOrmModule.forRootAsync({
        imports: [ConfigModule],
        inject: [ConfigService],
        useFactory: async (config: ConfigService) => {
console.log(config.get('DB_NAME'))  //for testing purpose only; returns undefined
          return {
            type: 'sqlite',
            database: config.get('DB_NAME'),
            entities: [User, Report],
            synchronize: true
          }
        }
      }), UsersModule, ReportsModule],
      controllers: [AppController],
      providers: [AppService, {
        provide: APP_PIPE,
        useValue: new ValidationPipe({ whitelist: true })
      }],
    })
</code>```

since config.get('DB_NAME') is undefined, database connection fails and in the console following error is thrown:

```<code>DriverOptionNotSetError: Driver option (database) is not set. Please set it to perform connection to the database.
</code>```

Also receiving undefined while trying to read COOKIE_SESSION env variable inside appModule  class using same this.configService.get('COOKIE_SESSION'). The configService in injected using a constructor inside appModule.

答:
try adding ConfigService in providers</p>
```<code>providers: [AppService, {
  provide: APP_PIPE,
  useValue: new ValidationPipe({ whitelist: true })
}, ConfigService]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to set TypeOrm configuration object using env variables in NestJS. The configuration object should read 'DB_NAME' env variable(set to db.sqlite) set in a .development.env file. The env variable is provided via configService.get('DB_NAME) api of @nestjs/config library. My code in app.module.ts files is as follows:

   import { ConfigModule, ConfigService } from '@nestjs/config';
    import { TypeOrmModule } from '@nestjs/typeorm';

    @Module({
      imports: [ConfigModule.forRoot({
        isGlobal: true,
        envFilePath: `.${process.env.NODE_ENV}.env`
      }), TypeOrmModule.forRootAsync({
        imports: [ConfigModule],
        inject: [ConfigService],
        useFactory: async (config: ConfigService) => {
console.log(config.get('DB_NAME'))  //for testing purpose only; returns undefined
          return {
            type: 'sqlite',
            database: config.get('DB_NAME'),
            entities: [User, Report],
            synchronize: true
          }
        }
      }), UsersModule, ReportsModule],
      controllers: [AppController],
      providers: [AppService, {
        provide: APP_PIPE,
        useValue: new ValidationPipe({ whitelist: true })
      }],
    })

since config.get('DB_NAME') is undefined, database connection fails and in the console following error is thrown:

DriverOptionNotSetError: Driver option (database) is not set. Please set it to perform connection to the database.

Also receiving undefined while trying to read COOKIE_SESSION env variable inside appModule  class using same this.configService.get('COOKIE_SESSION'). The configService in injected using a constructor inside appModule.

Body:
try adding ConfigService in providers

providers: [AppService, {
  provide: APP_PIPE,
  useValue: new ValidationPipe({ whitelist: true })
}, ConfigService]


问:
Using ++ operator in react component

import React, { useState } from "react";
// import styles sheet:
import "./css/CommentBlock.css";

// import profile avatars:
import gamer from "./icons/gamer.png";
import man1 from "./icons/man (1).png";
import man from "./icons/man.png";
import user from "./icons/user.png";
import woman1 from "./icons/woman (1).png";
import woman from "./icons/woman.png";

let icons = [gamer, man1, man, user, woman1, woman];
let index = 0;

function CommentBlock(props) {
  // JS object destructuring:
  let { name, comment } = props;
  index ++;
  console.log(index);

  return (

{name}

{comment}

  );
}

export default CommentBlock;```

index value: 1 3 5 7 9 11 ...

I'm really confused about ++ operator in react component.
I have 7 comment block but when I use index ++ in my component. I expect that index increases just one time. but index value increased for two times.

I want to know how solve this problem ?

答:
The problem you are facing is about react render (the lifecycle of react),
and the fact that in development mode, react uses Strict Mode, which causes a double render of your component, moreover, you are using a variable to hold your data, any render of your component cause the index increase, I think for your case you show use the react's state.

Strict mode can’t automatically detect side effects for you, but it
can help you spot them by making them a little more deterministic.
This is done by intentionally double-invoking the following functions:

Class component constructor, render, and shouldComponentUpdate methods
Class component static getDerivedStateFromProps method Function
component bodies State updater functions (the first argument to
setState) Functions passed to useState, useMemo, or useReducer Note:

This only applies to development mode. Lifecycles will not be
double-invoked in production mode.

https://reactjs.org/docs/strict-mode.html#gatsby-focus-wrapper

Taken from react official docs
you can read about the strict mode and more explained about the state and the lifecycle of react.

Title: Using ++ operator in react component

Body:
import React, { useState } from "react";
// import styles sheet:
import "./css/CommentBlock.css";

// import profile avatars:
import gamer from "./icons/gamer.png";
import man1 from "./icons/man (1).png";
import man from "./icons/man.png";
import user from "./icons/user.png";
import woman1 from "./icons/woman (1).png";
import woman from "./icons/woman.png";

let icons = [gamer, man1, man, user, woman1, woman];
let index = 0;

function CommentBlock(props) {
  // JS object destructuring:
  let { name, comment } = props;
  index ++;
  console.log(index);

  return (

{name}

{comment}

  );
}

export default CommentBlock;

index value: 1 3 5 7 9 11 ...

I'm really confused about ++ operator in react component.
I have 7 comment block but when I use index ++ in my component. I expect that index increases just one time. but index value increased for two times.

I want to know how solve this problem ?


问:
Having issue with container class in bootstrap?
Here is the link https://vkacademy.in/newm.html

When I create a container for every section I am getting space in between for every container, how to avoid the space for each container.

When you see the output I am getting space for each container that I highlighted. how to avoid the space?

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">

Bootstrap Tutorial

Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile-first projects on the web.

Bootstrap Tutorial

Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile-first projects on the web.

```

答:
Try this,
your problem in tag
, I add new class .mb-0

.one {
  background: red;
}

.two {
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="bg-danger">
    <h1>Bootstrap Tutorial</h1>
    <p class="mb-0">Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile-first projects on the web.</p>
  </div>
  <div class="container bg-success">
    <h1>Bootstrap Tutorial</h1>
    <p>Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile-first projects on the web.</p>
  </div>
</div></code>```

Body:
Try this,
your problem in tag <p>, I add new class .mb-0

.one {
  background: red;
}

.two {
  background: green;
}

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="bg-danger">
    <h1>Bootstrap Tutorial</h1>
    <p class="mb-0">Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile-first projects on the web.</p>
  </div>
  <div class="container bg-success">
    <h1>Bootstrap Tutorial</h1>
    <p>Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile-first projects on the web.</p>
  </div>
</div>


问:
Transfer Learning/Fine Tuning - how to keep BatchNormalization in inference mode?
In the following tutorial Transfer learning and fine-tuning by TensorFlow it is explained that that when unfreezing a model that contains BatchNormalization (BN) layers, these should be kept in inference mode by passing training=False when calling the base model.

[…]

Important notes about BatchNormalization layer

Many image models contain BatchNormalization layers. That layer is a special case on every imaginable count. Here are a few things to keep in mind.

BatchNormalization contains 2 non-trainable weights that get updated during training. These are the variables tracking the mean and variance of the inputs.

When you set bn_layer.trainable = False, the BatchNormalization layer will run in inference mode, and will not update its mean & variance statistics. This is not the case for other layers in general, as weight trainability & inference/training modes are two orthogonal concepts. But the two are tied in the case of the BatchNormalization layer.

When you unfreeze a model that contains BatchNormalization layers in order to do fine-tuning, you should keep the BatchNormalization layers in inference mode by passing training=False when calling the base model. Otherwise the updates applied to the non-trainable weights will suddenly destroy what the model has learned.

[…]

In the examples they pass training=False when calling the base model, but later they set base_model.trainable=True, which for my understanding is the opposite of inference mode, because the BN layers will be set to trainable as well.

For my understanding there would have to be 0 trainable_weights and 4 non_trainable_weights for inference mode, which would be identical to when setting the bn_layer.trainable=False, which they stated would be the case for running the bn_layer in inference mode.

I checked the number of trainable_weights and  number of non_trainable_weights and they are both 2.

I am confused by the tutorial, how can I really be sure BN layer are in inference mode when doing fine tuning on a model?

Does setting training=False on the model overwrite the behavior of bn_layer.trainable=True? So that even if the trainable_weights get listed with 2 these would not get updated during training (fine tuning)?

Update:

Here I found some further information: BatchNormalization layer - on keras.io.

[...]

About setting layer.trainable = False on a BatchNormalization layer:

The meaning of setting layer.trainable = False is to freeze the layer, i.e. its internal state will not change during training: its trainable weights will not be updated during fit() or train_on_batch(), and its state updates will not be run.

Usually, this does not necessarily mean that the layer is run in inference mode (which is normally controlled by the training argument that can be passed when calling a layer). "Frozen state" and "inference mode" are two separate concepts.

However, in the case of the BatchNormalization layer, setting trainable = False on the layer means that the layer will be subsequently run in inference mode (meaning that it will use the moving mean and the moving variance to normalize the current batch, rather than using the mean and variance of the current batch).

This behavior has been introduced in TensorFlow 2.0, in order to enable layer.trainable = False to produce the most commonly expected behavior in the convnet fine-tuning use case.

Note that: - Setting trainable on an model containing other layers will recursively set the trainable value of all inner layers. - If the value of the trainable attribute is changed after calling compile() on a model, the new value doesn't take effect for this model until compile() is called again.

Question:

In case I want to fine tune the whole model, so I am going to unfreeze the base_model.trainable = True, would I have to manually set the BN layers to bn_layer.trainable = False in order to keep them in inference mode?

What does happen when with the call of the base_model passing training=False and additionally setting base_model.trainable=True? Do layers like BatchNormalization and Dropout stay in inference mode?

答:
After reading the documentation and having a look on the source code of TensorFlows implementations of  tf.keras.layers.Layer, tf.keras.layers.Dense, and tf.keras.layers.BatchNormalization I got the following understanding.

If training = False is passed on calling the layer or the model/base model, it will run in inference mode. This has nothing to do with the attribute trainable, which means something different. It would probably lead to less misunderstanding, if they would have called the parameter training_mode instead of training. I would have preferred defining it the other way round and calling it inference_mode .

When doing Transfer Learning or Fine Tuning training = False should be passed on calling the base model itself. As far as I saw until now this will only affect layers like tf.keras.layers.Dropout and tf.keras.layers.BatchNormalization and will have not effect on the other layers.
Running in inference mode via training = False will result in:

tf.layers.Dropout not to apply the dropout rate at all. As tf.layers.Dropout has no trainable weights, setting the attribute trainable = False will have no effect at all on this layer.

tf.keras.layers.BatchNormalization normalizing its inputs using the mean and variance of its moving statistics learned during training

The attribute trainable will only activate or deactivate updating the trainable weights of a layer.


问:
When is it the right time to use C# class library (.dll)?
I'm a programmer who has never really used .dll files.
Of cause, when I need 3rd party software, such as a graphics library, a library to help me create graphs etc. I do add the references/ddl files to my program and use them in my code.

Also, it seems like you can use .dll for a lot of different things, so I'd like the topic to concentrate on C#.

Right now I am working on a sanitizing library(?) (I think that is the correct term), which will be full of relevant methods that can sanitize variables in all sorts of different ways.

What I want to know is:

would there be any advantage to:

1) Write the methods to class library -> compile/build it -> add the library as a reference to the program - which would need to sanitize some variables ?

Or would it be exactly the same if I where to:

2) Create a new SanitizeClass in the program -> add all the sanitize methods -> call the methods from the SanitizeClass in the different classes in the program that needs to sanitize variables

In general, I also want to know when it is an advantage to use compiled class libraries.
I'm thinking of speed, security, all of it.

Could anyone enlightenment me? :)

答:
Additional assemblies will add a slight load time and memory overhead, but otherwise have no performance implications.

Security will only make a difference if you need different code access security (CAS) and will make use of CAS.

Generally there are three reasons:

It makes things simpler. Putting everything in a single assembly is becoming unwieldy (this could include organisational/team issues).

Reuse.

You need separate assemblies. E.g. to have interfaces and implementation in different assemblies to allow AppDomains to be unloaded (e.g. for plugins).

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Richard

LastEditorDisplayName: Richard


问:
Is there a way to expand a JFileChooser directory without a mouse
Using a JFileChooser, I can select a directory by double clicking the directory (going down a level) with my mouse.  Is there a way to select a directory without the mouse?  For example, is there a key binding to go down a directory level or do I have to somehow add a key listener to the  JFileChooser? </p>

答: Have you tried the space-bar or enter key?</p>

ContentLicense: CC BY-SA 3.0


问:
java.lang.IllegalArgumentException: Cannot register after unregistered Filter class
I am developing login service using spring boo. when developing it I got below error and the class

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot register after unregistered Filter class com.jwt.logincservice.filter.JwtFilter

```<code>@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private MyUserDetailsService userDetailsService;

    @Autowired
    private Jwtutil jwtUtil;

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

        final String authorizationHeader = request.getHeader("Authorization");

        String username = null;
        String jwt = null;

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            username = jwtUtil.extractUsername(jwt);
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            if (jwtUtil.validateToken(jwt, userDetails)) {

                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        chain.doFilter(request, response);
    }
}
</code>```

WebSecurityConfigurerAdapter class

```<code>@EnableWebSecurity
public class SecurityConfigureAdapter extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserDetailsService myUseserDeatailService;

    @Autowired
    private JwtFilter jwtRequestFilter;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUseserDeatailService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests().antMatchers("/authentication").permitAll()
                .anyRequest().authenticated()
                .and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtRequestFilter, JwtFilter.class).authorizeRequests();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
</code>```

答: The list of filters to put in the *class part can be retrieved by increasing the debug level on spring security. Any filters there will work.</p>

Body:
I am developing login service using spring boo. when developing it I got below error and the class

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot register after unregistered Filter class com.jwt.logincservice.filter.JwtFilter

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private MyUserDetailsService userDetailsService;

    @Autowired
    private Jwtutil jwtUtil;

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

        final String authorizationHeader = request.getHeader("Authorization");

        String username = null;
        String jwt = null;

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            username = jwtUtil.extractUsername(jwt);
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            if (jwtUtil.validateToken(jwt, userDetails)) {

                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        chain.doFilter(request, response);
    }
}

WebSecurityConfigurerAdapter class

@EnableWebSecurity
public class SecurityConfigureAdapter extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserDetailsService myUseserDeatailService;

    @Autowired
    private JwtFilter jwtRequestFilter;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUseserDeatailService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests().antMatchers("/authentication").permitAll()
                .anyRequest().authenticated()
                .and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtRequestFilter, JwtFilter.class).authorizeRequests();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}


问:
decide the route based on the initialization phase of flutter_native_splash
I'm writing a flutter application using flutter 2.10 and I'm debugging it using an Android Emulator

I included the flutter_native_splash plugin from https://pub.dev/packages/flutter_native_splash and I use version 2.0.1+1

the problem that I'm having is that I decide what's the first screen that the user will see based on the initialization phase. I check the stored user token, see his premissions, verify them with the server, and forward him to him relevant route.

since the runApp() function executes in the background while the initialization phase is running I cannot choose the page that will be shown. and if I try to nativgate to a route in the initialization function I get an exception.

as a workaround for now I created an init_home route with FutureBuilder that awaits for a global variable called GeneralService.defaultRoute to be set and then changes the route.

```<code>class _InitHomeState extends State<InitHome> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<dynamic>(
        future: () async {
          var waitCount=0;
          while (GeneralService.defaultRoute  == "") {
            waitCount++;
            await Future.delayed(const Duration(milliseconds: 100));
            if (waitCount>20) {
              break;
            }
          }
          if (GeneralService.defaultRoute == "") {
            return Future.error("initialization failed");
          }
          Navigator.of(context).pushReplacementNamed(GeneralService.defaultRoute);
          ...
</code>```

any ideas how to resolve this issue properly ?

答:
I use a Stateful widget as Splash Screen.
In the build method, you just return the 'loading' view such as Container with a background color etc. (with texts or whatever you like but just consider it as the loading screen).

In the initState(), you call a function that we can name redirect(). This should be an async function that performs the queries/checks and at the end, calls the Navigator.of(context).pushReplacementNamed etc.

```<code>class _SplashState extends State<Splash> {
  @override
  void initState() {
    super.initState();
    redirect();
  }

  @override
  Widget build(BuildContext context) {
     return Container(color: Colors.blue);
  }

  Future<void> redirect() async {
    var name = 'LOGIN';
    ... // make db calls, checks etc
    Navigator.of(context).pushReplacementNamed(name);
  }
}
</code>```

Your build function just creates the loading UI, and the redirect function in the initState is the one running in the background and when it has finished computing, calls the Navigator.push to your desired page.

Body:
I'm writing a flutter application using flutter 2.10 and I'm debugging it using an Android Emulator

I included the flutter_native_splash plugin from https://pub.dev/packages/flutter_native_splash and I use version 2.0.1+1

the problem that I'm having is that I decide what's the first screen that the user will see based on the initialization phase. I check the stored user token, see his premissions, verify them with the server, and forward him to him relevant route.

since the runApp() function executes in the background while the initialization phase is running I cannot choose the page that will be shown. and if I try to nativgate to a route in the initialization function I get an exception.

as a workaround for now I created an init_home route with FutureBuilder that awaits for a global variable called GeneralService.defaultRoute to be set and then changes the route.

class _InitHomeState extends State<InitHome> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<dynamic>(
        future: () async {
          var waitCount=0;
          while (GeneralService.defaultRoute  == "") {
            waitCount++;
            await Future.delayed(const Duration(milliseconds: 100));
            if (waitCount>20) {
              break;
            }
          }
          if (GeneralService.defaultRoute == "") {
            return Future.error("initialization failed");
          }
          Navigator.of(context).pushReplacementNamed(GeneralService.defaultRoute);
          ...

any ideas how to resolve this issue properly ?

Body:
I use a Stateful widget as Splash Screen.
In the build method, you just return the 'loading' view such as Container with a background color etc. (with texts or whatever you like but just consider it as the loading screen).

In the initState(), you call a function that we can name redirect(). This should be an async function that performs the queries/checks and at the end, calls the Navigator.of(context).pushReplacementNamed etc.

class _SplashState extends State<Splash> {
  @override
  void initState() {
    super.initState();
    redirect();
  }

  @override
  Widget build(BuildContext context) {
     return Container(color: Colors.blue);
  }

  Future<void> redirect() async {
    var name = 'LOGIN';
    ... // make db calls, checks etc
    Navigator.of(context).pushReplacementNamed(name);
  }
}

Your build function just creates the loading UI, and the redirect function in the initState is the one running in the background and when it has finished computing, calls the Navigator.push to your desired page.


问:
Nextjs: update value with use
This is my code:

```<code>export default function useUser(){
    var userToken = "one"

    function setToken(value: string) {
        userToken = value
    }

    return { userToken, setToken }
}
</code>```

And this is my home:

```<code>export default function Home() {
    const { userToken, setToken } = useUser()

    console.log(userToken)
    setAccessToken("two");
    console.log(userToken)
}
</code>```

I want to my result be: one two

But my code return: one one

答:
The userToken is just a value output from the useUser call. As oppsed to that setToken is a function that has access to closure of useUser. To get it work as you expect add a getter method called getToken which will have access to the closure of useUser function.

function useUser() {
  var userToken = "one";

  function setToken(value) {
    userToken = value;
  }

  function getToken() {
    return userToken;
  }

  return { getToken, setToken };
}

function Home() {
  const { getToken, setToken } = useUser();

  console.log(getToken());
  setToken("two");
  console.log(getToken());

  return (

      {getToken()}{" "}
      <button
        onClick={() => {
          setToken("three");
          console.log(getToken());
        }}
      >
        click me
      </button>

  );
}

ReactDOM.render(<Home/>, document.getElementById("root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div></code>```

But still, it will not re-render anything for you after the button click. This is due to how React works it only renders when state changes. You should use useState hook for that.

Title: Nextjs: update value with use

Body:
This is my code:

export default function useUser(){
    var userToken = "one"

    function setToken(value: string) {
        userToken = value
    }

    return { userToken, setToken }
}

And this is my home:

export default function Home() {
    const { userToken, setToken } = useUser()

    console.log(userToken)
    setAccessToken("two");
    console.log(userToken)
}

I want to my result be: one two

But my code return: one one

Body:
The userToken is just a value output from the useUser call. As oppsed to that setToken is a function that has access to closure of useUser. To get it work as you expect add a getter method called getToken which will have access to the closure of useUser function.

function useUser() {
  var userToken = "one";

  function setToken(value) {
    userToken = value;
  }

  function getToken() {
    return userToken;
  }

  return { getToken, setToken };
}

function Home() {
  const { getToken, setToken } = useUser();

  console.log(getToken());
  setToken("two");
  console.log(getToken());

  return (
    <div>
      {getToken()}{" "}
      <button
        onClick={() => {
          setToken("three");
          console.log(getToken());
        }}
      >
        click me
      </button>
    </div>
  );
}

ReactDOM.render(<Home/>, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

But still, it will not re-render anything for you after the button click. This is due to how React works it only renders when state changes. You should use useState hook for that.


问:
How we can retrieve the data of the checkboxes in another activity in a text view
This is the activity where I defined the checkboxes and Array list.
I have save the result in the arraylist and want to display the same arraylist in another activity.

```<code>   public ArrayList<String> Result;

   Result = new ArrayList<>();

   public void statuscheck(){

    bcg.setOnClickListener(v -> {
        if(bcg.isChecked()){
            Result.add("BCG(Bacillus Calmette and Guérin)");
        }
        else {
            Result.remove("BCG(Bacillus Calmette and Guérin)");
        }
    });

    bopv0.setOnClickListener(v -> {
        if(bopv0.isChecked()){
            Result.add("b Oral Polio vaccine(bOPV)-0 ");
        }
        else {
            Result.remove("b Oral Polio vaccine(bOPV)-0 ");
        }
    });

    hepatitis0.setOnClickListener(v -> {
        if(hepatitis0.isChecked()){

            Result.add("Hepatitis B birth dose ");

        }

        else {

            Result.remove("Hepatitis B birth dose ");

        }

    });
}
</code>```

the activity where I want to show the arraylist in a text view

```<code>TextView vac_result;
ArrayList<String> vc_Res;

    vac_result = findViewById(R.id.vac_result);
    vac_result.setEnabled(false);

    vc_Res = vaccineone.Result;
    StringBuilder stringBuilder = new StringBuilder();
    for(String s : vc_Res)
        stringBuilder.append("\n");

    vac_result.setText(stringBuilder.toString());
    vac_result.setEnabled(true);
</code>```

答: Save the "Result" ArrayList with SharedPreferences and in the other activity load the data before trying to work with it.</p>

Body:
This is the activity where I defined the checkboxes and Array list.
I have save the result in the arraylist and want to display the same arraylist in another activity.

   public ArrayList<String> Result;

   Result = new ArrayList<>();

   public void statuscheck(){

    bcg.setOnClickListener(v -> {
        if(bcg.isChecked()){
            Result.add("BCG(Bacillus Calmette and Guérin)");
        }
        else {
            Result.remove("BCG(Bacillus Calmette and Guérin)");
        }
    });

    bopv0.setOnClickListener(v -> {
        if(bopv0.isChecked()){
            Result.add("b Oral Polio vaccine(bOPV)-0 ");
        }
        else {
            Result.remove("b Oral Polio vaccine(bOPV)-0 ");
        }
    });

    hepatitis0.setOnClickListener(v -> {
        if(hepatitis0.isChecked()){

            Result.add("Hepatitis B birth dose ");

        }

        else {

            Result.remove("Hepatitis B birth dose ");

        }

    });
}

the activity where I want to show the arraylist in a text view

TextView vac_result;
ArrayList<String> vc_Res;

    vac_result = findViewById(R.id.vac_result);
    vac_result.setEnabled(false);

    vc_Res = vaccineone.Result;
    StringBuilder stringBuilder = new StringBuilder();
    for(String s : vc_Res)
        stringBuilder.append("\n");

    vac_result.setText(stringBuilder.toString());
    vac_result.setEnabled(true);


问:
update_attributes on nested forms does not work
I have a nested form and trying to update it using update_attributes but it doesnt seem to work. I am using rails 2.3.8

Can you please help?

Aanu

adding some code

controller code:

```<code>update
@app.update_attributes(params[:application])
end
</code>```

@_params:

```<code>{"authenticity_token"=>"AdSr8o51u7GfnOwLSpEOe5xAPINd7ImxDpuayPk12No=", "_method"=>"put", "action"=>"update", "id"=>"10006", "stype"=>"Save",
"application"=>{
    "contact_attributes"=>{"city"=>"Denver", "address"=>"7000 Drive", "zip"=>"22222", "first_name"=>"Randy"}, "details_attributes"=>{
        "2"=>{ "coverage"=>"false", "same_fee"=>"true", "fee_rate"=>"2000", "id"=>"10018", "year_estabilished"=>"2005"}
    }}
}
</code>```

答: Well, do you have accepts_nested_attributes_for defined in your model? Have a look here: http://apidock.com/rails/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for

Body:
I have a nested form and trying to update it using update_attributes but it doesnt seem to work. I am using rails 2.3.8

Can you please help?

Aanu

adding some code

controller code:

update
@app.update_attributes(params[:application])
end

@_params:

{"authenticity_token"=>"AdSr8o51u7GfnOwLSpEOe5xAPINd7ImxDpuayPk12No=", "_method"=>"put", "action"=>"update", "id"=>"10006", "stype"=>"Save",
"application"=>{
    "contact_attributes"=>{"city"=>"Denver", "address"=>"7000 Drive", "zip"=>"22222", "first_name"=>"Randy"}, "details_attributes"=>{
        "2"=>{ "coverage"=>"false", "same_fee"=>"true", "fee_rate"=>"2000", "id"=>"10018", "year_estabilished"=>"2005"}
    }}
}


问:
How to implement responsive width for Drawer MUI v5 component?
I am using Material UI v5, and am trying to make a responsive drawer where for smaller devices it will take up 100% of screen width while for larger devices it should only take 1/3 of screen width. But I have no idea how to access Paper property to modify the actual width and make it responsive.

My code:

```<code>import { Drawer, styled } from "@mui/material";

const ResponsiveDrawer = styled(Drawer)(({ theme }) => ({
  [theme.breakpoints.up("md")]: {
    width: "33%", // THIS ONLY CHANGES DRAWER WIDTH NOT PAPER WIDTH INSIDE THE DRAWER
  },
  [theme.breakpoints.down("md")]: {
    width: "100%",
  },
}));

export { ResponsiveDrawer };
</code>```

How I use it:

```<code>import { ResponsiveDrawer } from "./Style";

<ResponsiveDrawer
            anchor="right"
            open={drawer.state}
            onClose={() => drawer.onClick(false)}
        >
            ...
</ResponsiveDrawer>
</code>```

答:
You can add a div inside the <Drawer> or <SwipeableDrawer> component like so and control the width of the div through CSS (or emotion/styled, if you prefer).

```<code><Drawer ...>
  <div className="container">...</div>
</Drawer>
</code>```

.container {
  width: 95vw; // for mobile

  ... add media queries for rest of the screen sizes here
}
```

Body:
I am using Material UI v5, and am trying to make a responsive drawer where for smaller devices it will take up 100% of screen width while for larger devices it should only take 1/3 of screen width. But I have no idea how to access Paper property to modify the actual width and make it responsive.

My code:

import { Drawer, styled } from "@mui/material";

const ResponsiveDrawer = styled(Drawer)(({ theme }) => ({
  [theme.breakpoints.up("md")]: {
    width: "33%", // THIS ONLY CHANGES DRAWER WIDTH NOT PAPER WIDTH INSIDE THE DRAWER
  },
  [theme.breakpoints.down("md")]: {
    width: "100%",
  },
}));

export { ResponsiveDrawer };

How I use it:

import { ResponsiveDrawer } from "./Style";

<ResponsiveDrawer
            anchor="right"
            open={drawer.state}
            onClose={() => drawer.onClick(false)}
        >
            ...
</ResponsiveDrawer>

Body:
You can add a div inside the <Drawer> or <SwipeableDrawer> component like so and control the width of the div through CSS (or emotion/styled, if you prefer).

<Drawer ...>
  <div className="container">...</div>
</Drawer>

.container {
  width: 95vw; // for mobile

  ... add media queries for rest of the screen sizes here
}


问:
I want to insert with mikro-orm, but it dont find my table :c (TableNotFoundException)
So

Console:

```<code>yarn dev
yarn run v1.22.10
$ nodemon dist/index.js
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node dist/index.js`
[discovery] ORM entity discovery started, using ReflectMetadataProvider
[discovery] - processing entity Post
[discovery] - entity discovery finished, found 1 entities, took 21 ms
[info] MikroORM successfully connected to database postgres on postgresql://postgres:*****@127.0.0.1:5432
[query] begin
[query] insert into "post" ("created_at", "title", "updated_at") values ('2021-04-05T21:04:23.126Z', 'my first post', '2021-04-05T21:04:23.126Z') returning "_id" [took 12 ms]
[query] rollback
TableNotFoundException: insert into "post" ("created_at", "title", "updated_at") values ('2021-04-05T21:04:23.126Z', 'my first post', '2021-04-05T21:04:23.126Z') returning "_id" - relation "post" does not exist
    at PostgreSqlExceptionConverter.convertException (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\postgresql\PostgreSqlExceptionConverter.js:36:24)
    at PostgreSqlDriver.convertException (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\drivers\DatabaseDriver.js:194:54)
    at P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\drivers\DatabaseDriver.js:198:24
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async PostgreSqlDriver.nativeInsert (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\knex\AbstractSqlDriver.js:150:21)
    at async ChangeSetPersister.persistNewEntity (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\unit-of-work\ChangeSetPersister.js:55:21)
    at async ChangeSetPersister.executeInserts (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\unit-of-work\ChangeSetPersister.js:24:13)
    at async UnitOfWork.commitCreateChangeSets (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\unit-of-work\UnitOfWork.js:496:9)
    at async UnitOfWork.persistToDatabase (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\unit-of-work\UnitOfWork.js:458:13)
    at async PostgreSqlConnection.transactional (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\knex\AbstractSqlConnection.js:53:25)
    at async UnitOfWork.commit (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\unit-of-work\UnitOfWork.js:183:17)
    at async SqlEntityManager.flush (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\EntityManager.js:486:9)
    at async SqlEntityManager.persistAndFlush (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\EntityManager.js:438:9)

previous error: insert into "post" ("created_at", "title", "updated_at") values ('2021-04-05T21:04:23.126Z', 'my
first post', '2021-04-05T21:04:23.126Z') returning "_id" - relation "post" does not exist
    at Parser.parseErrorMessage (P:\.Projektek\lireddit-server\node_modules\pg-protocol\dist\parser.js:278:15)
    at Parser.handlePacket (P:\.Projektek\lireddit-server\node_modules\pg-protocol\dist\parser.js:126:29)
    at Parser.parse (P:\.Projektek\lireddit-server\node_modules\pg-protocol\dist\parser.js:39:38)
    at Socket.<anonymous> (P:\.Projektek\lireddit-server\node_modules\pg-protocol\dist\index.js:10:42)
    at Socket.emit (events.js:315:20)
    at Socket.EventEmitter.emit (domain.js:467:12)
    at addChunk (internal/streams/readable.js:309:12)
    at readableAddChunk (internal/streams/readable.js:284:9)
    at Socket.Readable.push (internal/streams/readable.js:223:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:188:23) {
  length: 166,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: '13',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'd:\\pginstaller_13.auto\\postgres.windows-x64\\src\\backend\\parser\\parse_relation.c',
  line: '1376',
  routine: 'parserOpenTable'
}
</code>```

Index.ts:

```<code>import { MikroORM } from "@mikro-orm/core";
import { __prod__ } from "./constants";
import { Post } from "./entities/Post";
import mikroConfig from "./mikro-orm.config";

const main = async () => {
  const orm = await MikroORM.init(mikroConfig);
  await orm.getMigrator().up;
  const post = orm.em.create(Post, { title: "my first post" });
  await orm.em.persistAndFlush(post);
};

main().catch((err) => {
  console.error(err);
});
</code>```

Post.ts:

```<code>import { Entity, PrimaryKey, Property } from "@mikro-orm/core";

@Entity()
export class Post {
  @PrimaryKey()
  _id!: number;

  @Property({ type: "date" })
  createdAt = new Date();

  @Property({ type: "date", onUpdate: () => new Date() })
  updatedAt = new Date();

  @Property({ type: "text" })
  title!: string;
}
</code>```

mikro-orm.config.ts:

```<code>import { __prod__ } from "./constants";
import { Post } from "./entities/Post";
import { MikroORM } from "@mikro-orm/core";
import path from "path";

export default {
  migrations: {
    path: path.join(__dirname, "./migrations"),
    pattern: /^[\w-]+\d+\.[tj]s$/,
  },
  entities: [Post],
  dbName: "postgres",
  debug: !__prod__,
  type: "postgresql",
  password: "hellothere",
} as Parameters<typeof MikroORM.init>[0];
</code>```

And the migration I created with npx mikro-orm migration:create:

```<code>import { Migration } from '@mikro-orm/migrations';

export class Migration20210405205411 extends Migration {

  async up(): Promise<void> {
    this.addSql('create table "post" ("_id" serial primary key, "created_at" timestamptz(0) not null, "updated_at" timestamptz(0) not null, "title" text not null);');
  }

}
</code>```

After that im compiling it to js btw, but I guess the problem will be somewhere at my code or idk plz help me, I can give you more info just plz help, I've been trying to fix this bug for 5 hours :/

Btw Im doin Ben Awad's 14 hour fullstack tutorial if its matter.

答:
I also experienced this. And like Fares47 said it's possibly because I passed the username and password in ./mikro-orm.config.ts.

And my solution is simply execute the sql command that generated in ./src/migrations/Migration<NUMBERS>.ts file in postgresql terminal.
Here is the command that I execute in the database,

```<code>create table "post" ("id" serial primary key, "created_at" timestamptz(0) not null, "updated_at" timestamptz(0) not null, "title" text not null);
</code>```

Just like what they suggested in the doc,

A safe approach would be generating the SQL on development server and
saving it into SQL Migration files that are executed manually on the
production server.

Body:
So

Console:

yarn dev
yarn run v1.22.10
$ nodemon dist/index.js
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node dist/index.js`
[discovery] ORM entity discovery started, using ReflectMetadataProvider
[discovery] - processing entity Post
[discovery] - entity discovery finished, found 1 entities, took 21 ms
[info] MikroORM successfully connected to database postgres on postgresql://postgres:*****@127.0.0.1:5432
[query] begin
[query] insert into "post" ("created_at", "title", "updated_at") values ('2021-04-05T21:04:23.126Z', 'my first post', '2021-04-05T21:04:23.126Z') returning "_id" [took 12 ms]
[query] rollback
TableNotFoundException: insert into "post" ("created_at", "title", "updated_at") values ('2021-04-05T21:04:23.126Z', 'my first post', '2021-04-05T21:04:23.126Z') returning "_id" - relation "post" does not exist
    at PostgreSqlExceptionConverter.convertException (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\postgresql\PostgreSqlExceptionConverter.js:36:24)
    at PostgreSqlDriver.convertException (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\drivers\DatabaseDriver.js:194:54)
    at P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\drivers\DatabaseDriver.js:198:24
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async PostgreSqlDriver.nativeInsert (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\knex\AbstractSqlDriver.js:150:21)
    at async ChangeSetPersister.persistNewEntity (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\unit-of-work\ChangeSetPersister.js:55:21)
    at async ChangeSetPersister.executeInserts (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\unit-of-work\ChangeSetPersister.js:24:13)
    at async UnitOfWork.commitCreateChangeSets (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\unit-of-work\UnitOfWork.js:496:9)
    at async UnitOfWork.persistToDatabase (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\unit-of-work\UnitOfWork.js:458:13)
    at async PostgreSqlConnection.transactional (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\knex\AbstractSqlConnection.js:53:25)
    at async UnitOfWork.commit (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\unit-of-work\UnitOfWork.js:183:17)
    at async SqlEntityManager.flush (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\EntityManager.js:486:9)
    at async SqlEntityManager.persistAndFlush (P:\.Projektek\lireddit-server\node_modules\@mikro-orm\core\EntityManager.js:438:9)

previous error: insert into "post" ("created_at", "title", "updated_at") values ('2021-04-05T21:04:23.126Z', 'my
first post', '2021-04-05T21:04:23.126Z') returning "_id" - relation "post" does not exist
    at Parser.parseErrorMessage (P:\.Projektek\lireddit-server\node_modules\pg-protocol\dist\parser.js:278:15)
    at Parser.handlePacket (P:\.Projektek\lireddit-server\node_modules\pg-protocol\dist\parser.js:126:29)
    at Parser.parse (P:\.Projektek\lireddit-server\node_modules\pg-protocol\dist\parser.js:39:38)
    at Socket.<anonymous> (P:\.Projektek\lireddit-server\node_modules\pg-protocol\dist\index.js:10:42)
    at Socket.emit (events.js:315:20)
    at Socket.EventEmitter.emit (domain.js:467:12)
    at addChunk (internal/streams/readable.js:309:12)
    at readableAddChunk (internal/streams/readable.js:284:9)
    at Socket.Readable.push (internal/streams/readable.js:223:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:188:23) {
  length: 166,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: '13',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'd:\\pginstaller_13.auto\\postgres.windows-x64\\src\\backend\\parser\\parse_relation.c',
  line: '1376',
  routine: 'parserOpenTable'
}

Index.ts:

import { MikroORM } from "@mikro-orm/core";
import { __prod__ } from "./constants";
import { Post } from "./entities/Post";
import mikroConfig from "./mikro-orm.config";

const main = async () => {
  const orm = await MikroORM.init(mikroConfig);
  await orm.getMigrator().up;
  const post = orm.em.create(Post, { title: "my first post" });
  await orm.em.persistAndFlush(post);
};

main().catch((err) => {
  console.error(err);
});

Post.ts:

import { Entity, PrimaryKey, Property } from "@mikro-orm/core";

@Entity()
export class Post {
  @PrimaryKey()
  _id!: number;

  @Property({ type: "date" })
  createdAt = new Date();

  @Property({ type: "date", onUpdate: () => new Date() })
  updatedAt = new Date();

  @Property({ type: "text" })
  title!: string;
}

mikro-orm.config.ts:

import { __prod__ } from "./constants";
import { Post } from "./entities/Post";
import { MikroORM } from "@mikro-orm/core";
import path from "path";

export default {
  migrations: {
    path: path.join(__dirname, "./migrations"),
    pattern: /^[\w-]+\d+\.[tj]s$/,
  },
  entities: [Post],
  dbName: "postgres",
  debug: !__prod__,
  type: "postgresql",
  password: "hellothere",
} as Parameters<typeof MikroORM.init>[0];

And the migration I created with npx mikro-orm migration:create:

import { Migration } from '@mikro-orm/migrations';

export class Migration20210405205411 extends Migration {

  async up(): Promise<void> {
    this.addSql('create table "post" ("_id" serial primary key, "created_at" timestamptz(0) not null, "updated_at" timestamptz(0) not null, "title" text not null);');
  }

}

After that im compiling it to js btw, but I guess the problem will be somewhere at my code or idk plz help me, I can give you more info just plz help, I've been trying to fix this bug for 5 hours :/

Btw Im doin Ben Awad's 14 hour fullstack tutorial if its matter.

Body:
I also experienced this. And like Fares47 said it's possibly because I passed the username and password in ./mikro-orm.config.ts.

And my solution is simply execute the sql command that generated in ./src/migrations/Migration<NUMBERS>.ts file in postgresql terminal.
Here is the command that I execute in the database,

create table "post" ("id" serial primary key, "created_at" timestamptz(0) not null, "updated_at" timestamptz(0) not null, "title" text not null);

Just like what they suggested in the doc,

A safe approach would be generating the SQL on development server and
saving it into SQL Migration files that are executed manually on the
production server.


问:
HTML5 make empty div full viewport size
I’m trying to create an EMPTY div that takes up 100% of the viewport and that moves with the viewport (or position: fixed).
It also needs to be at top: 0, left 0 of the viewport. This is for a browser extension so I need this div to be added over any page.

The background reason for this is so I can use the div as a full page tooltip that shows the mouse x and y positions and the tooltip follows the mouse.

How can this full page div be achieved? My many attempts have failed to create a div with any height.

I am away from my pc but can add what I’ve tried already soon.

答:
Try this</p>
```<code>{
  position: fixed;
  height: 100vh;
  width: 100vw;
}
</code>```

Title: HTML5 make empty div full viewport size

Body:
Try this

{
  position: fixed;
  height: 100vh;
  width: 100vw;
}


问:
tkinter insert and delete function
I have started experimenting with tkinter a little. Right now im trying to build a simple calculator and for that I used the delete and insert function to clear the Entry.

This is the command I used:

```<code>t1.delete(1.0, 'end')
</code>```

My question: What is the meaning of '1.0' and the 'end'?

答:
Tkinter Text widget has delete(first, last=None) method to delete the characters at the index of first, or within the range of (first, last) from the text box.

Visit this link:  what is the meaning of '1.0' and the 'end'

Title: tkinter insert and delete function

Body:
I have started experimenting with tkinter a little. Right now im trying to build a simple calculator and for that I used the delete and insert function to clear the Entry.

This is the command I used:

t1.delete(1.0, 'end')

My question: What is the meaning of '1.0' and the 'end'?


问:
Can I use a Kotlin Contract to guarantee the non-nullity of another property?
I have a class with a nullable property description: String?, and for convenience would like to expose a fun hasDescription(): Boolean that null-checks said String.

For even more convenience, I am hoping to use a contract so I can smart cast description to non-nullable String after checking hasDescription().

Is this possible now (with experimental contracts, and Kotlin 1.5)?

Might it be possible when contracts go stable?

```<code>data class Widget (
    val description: String? = null,
)

class Gadget {
    val widget: Widget? = null

    val description: String? get() = widget?.description

    @ExperimentalContracts
    fun hasDescription(): Boolean {
        // Error in contract description: only references to
        // parameters are allowed in contract description
        contract {
            returns(true) implies((this@Gadget).description is String)
        }

        return this.description != null
    }
}

@ExperimentalContracts
fun testContract(gadget: Gadget) {
    if (gadget.hasDescription()) {
        // Error: Type mismatch (String? for String)
        // expected, since the contract itself does not compile
        val description: String = gadget.description
    }
}
</code>```

答:
In short, it's not possible.

Contracts primarily consider the behavior of methods rather than the properties of values. Properties of values should be handled by the type system rather than contracts.

And yes, it might be implemented in the future.

It doesn't mean that if something potentially can be handled by the type system, then it is out of contracts' scope.

https://github.com/Kotlin/KEEP/blob/master/proposals/kotlin-contracts.md#scope-and-restrictions

Alternatives

Nulls are well handled in Kotlin's type system, and so we can use that to check for nullability.

Smart casting

Using smart-casting would remove the need for Contracts and the hasDescription()
method.

fun nullCheckWhen(gadget: Gadget) {
  when (val description = gadget.description) {
    null -> println("description is null")
    else -> println("description.length ${description.length}")
  }
}
```
<pre class="lang-kotlin prettyprint-override"><code>fun earlyReturn(gadget: Gadget) {
  val description = gadget.description ?: return

  println("description.length ${description.length}")
}
</code>```

fun forcefulNullCheck(gadget: Gadget) {

  val description = requireNotNull(gadget.description) {
    "description must not be null"
  }

  println("description.length ${description.length}")
}
```
<pre class="lang-kotlin prettyprint-override"><code>fun elvisScopeFunctionNullSafe(gadget: Gadget) {

  gadget.widget?.description?.let { description ->
    println("description.length ${description.length}")
  }

}
</code>```

These are a little more clunky, and not as pretty as Contracts could be - but at least they work.

In fact, some of them use Kotlin Contracts, but of course they can only work on method parameters.

Preconditions.kt

/**
 * Throws an [IllegalArgumentException] if the [value] is null. Otherwise returns the not null value.
 */
@kotlin.internal.InlineOnly
public inline fun <T : Any> requireNotNull(value: T?): T {
  contract {
    returns() implies (value != null)
  }
  return requireNotNull(value) { "Required value was null." }
}
```
<h4>Type hierarchies</h4>
<p>I don't think this approach is applicable to your situation, but I thought I'd share it as it can be useful.</p>
<p>If <code>description</code> was defined in an interface as a <code>String?</code>, then <code>Widget</code> could implement <code>description</code> as a non-nullable <code>String</code>. This works because in Kotlin the nullable type is a super-type of the non-nullable type. Any implementation of <code>description</code> can choose to be either be <code>String?</code> or <code>String</code>.</p>
<pre class="lang-kotlin prettyprint-override"><code>interface Component {
  val description: String?
}

data class Widget(
  override val description: String
) : Component

data class Greeble(
  override val description: String?
) : Component

fun nullCheckGeneric(component: Component) {

  when (component) {
    is Widget  ->
      // no need for a null check
      println("description.length ${component.description.length}")
    is Greeble ->
      // description is nullable
      println("description.length ${component.description?.length}")
  }

}
</code>```

Body:
I have a class with a nullable property description: String?, and for convenience would like to expose a fun hasDescription(): Boolean that null-checks said String.

For even more convenience, I am hoping to use a contract so I can smart cast description to non-nullable String after checking hasDescription().

Is this possible now (with experimental contracts, and Kotlin 1.5)?

Might it be possible when contracts go stable?

data class Widget (
    val description: String? = null,
)

class Gadget {
    val widget: Widget? = null

    val description: String? get() = widget?.description

    @ExperimentalContracts
    fun hasDescription(): Boolean {
        // Error in contract description: only references to
        // parameters are allowed in contract description
        contract {
            returns(true) implies((this@Gadget).description is String)
        }

        return this.description != null
    }
}

@ExperimentalContracts
fun testContract(gadget: Gadget) {
    if (gadget.hasDescription()) {
        // Error: Type mismatch (String? for String)
        // expected, since the contract itself does not compile
        val description: String = gadget.description
    }
}

Body:
In short, it's not possible.

Contracts primarily consider the behavior of methods rather than the properties of values. Properties of values should be handled by the type system rather than contracts.

And yes, it might be implemented in the future.

It doesn't mean that if something potentially can be handled by the type system, then it is out of contracts' scope.

https://github.com/Kotlin/KEEP/blob/master/proposals/kotlin-contracts.md#scope-and-restrictions

Alternatives

Nulls are well handled in Kotlin's type system, and so we can use that to check for nullability.

Smart casting

Using smart-casting would remove the need for Contracts and the hasDescription()
method.

fun nullCheckWhen(gadget: Gadget) {
  when (val description = gadget.description) {
    null -> println("description is null")
    else -> println("description.length ${description.length}")
  }
}

fun earlyReturn(gadget: Gadget) {
  val description = gadget.description ?: return

  println("description.length ${description.length}")
}

fun forcefulNullCheck(gadget: Gadget) {

  val description = requireNotNull(gadget.description) {
    "description must not be null"
  }

  println("description.length ${description.length}")
}

fun elvisScopeFunctionNullSafe(gadget: Gadget) {

  gadget.widget?.description?.let { description ->
    println("description.length ${description.length}")
  }

}

These are a little more clunky, and not as pretty as Contracts could be - but at least they work.

In fact, some of them use Kotlin Contracts, but of course they can only work on method parameters.

Preconditions.kt

/**
 * Throws an [IllegalArgumentException] if the [value] is null. Otherwise returns the not null value.
 */
@kotlin.internal.InlineOnly
public inline fun <T : Any> requireNotNull(value: T?): T {
  contract {
    returns() implies (value != null)
  }
  return requireNotNull(value) { "Required value was null." }
}

Type hierarchies

I don't think this approach is applicable to your situation, but I thought I'd share it as it can be useful.

If description was defined in an interface as a String?, then Widget could implement description as a non-nullable String. This works because in Kotlin the nullable type is a super-type of the non-nullable type. Any implementation of description can choose to be either be String? or String.

interface Component {
  val description: String?
}

data class Widget(
  override val description: String
) : Component

data class Greeble(
  override val description: String?
) : Component

fun nullCheckGeneric(component: Component) {

  when (component) {
    is Widget  ->
      // no need for a null check
      println("description.length ${component.description.length}")
    is Greeble ->
      // description is nullable
      println("description.length ${component.description?.length}")
  }

}


问:
How to fetch data from mongoDB based on two dates in spring boot?
I'm using Aggregation in spring boot. but getting response as null

```<code>Aggregation.match(Criteria.where("createdAt").lt(fromDate).gt(toDate));
</code>```

mongoDbTemplate returning query as follows

```<code>"createdAt" : { "$gt" : { "$date" : "2020-12-31T18:30:00.000Z"} , "$lt" : { "$date" : "2022-01-04T07:34:42.000Z"}}}}
</code>```

so how to fetch data from MongoDB using mongoTemplate.aggregation.
$date is not supported in mongo Shell,
is there any solution for this?

答:
After lots of researh finally, I got the solution, probably this will help others.

```<code>"createdAt" : { "$gt" : { "$date" : "2020-12-31T18:30:00.000Z"} , "$lt" : { "$date" : "2022-01-04T07:34:42.000Z"}}}}
</code>```

This is returned by mongoDbTemplate is right but it's not supporting the older version of spring boot.

My project older version was

```<code><pom>
    <groupId>com.Demo</groupId>
    <artifactId>emp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
</pom>
</code>```

I change it as follows

```<code> <pom>
        <groupId>com.Demo</groupId>
        <artifactId>emp</artifactId>
        <version>2.5.3</version>
        <packaging>war</packaging>
  </pom>
</code>```

The rest of the code is the same as above.

So it's working fine.

Body:
I'm using Aggregation in spring boot. but getting response as null

Aggregation.match(Criteria.where("createdAt").lt(fromDate).gt(toDate));

mongoDbTemplate returning query as follows

"createdAt" : { "$gt" : { "$date" : "2020-12-31T18:30:00.000Z"} , "$lt" : { "$date" : "2022-01-04T07:34:42.000Z"}}}}

so how to fetch data from MongoDB using mongoTemplate.aggregation.
$date is not supported in mongo Shell,
is there any solution for this?

Body:
After lots of researh finally, I got the solution, probably this will help others.

"createdAt" : { "$gt" : { "$date" : "2020-12-31T18:30:00.000Z"} , "$lt" : { "$date" : "2022-01-04T07:34:42.000Z"}}}}

This is returned by mongoDbTemplate is right but it's not supporting the older version of spring boot.

My project older version was

<pom>
    <groupId>com.Demo</groupId>
    <artifactId>emp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
</pom>

I change it as follows

 <pom>
        <groupId>com.Demo</groupId>
        <artifactId>emp</artifactId>
        <version>2.5.3</version>
        <packaging>war</packaging>
  </pom>

The rest of the code is the same as above.

So it's working fine.


Title: Pandas resample to weekly while last index is the end of that month

Body:
I got the following dataframe containing daily data and I would like to resample it to weekly data.

            Name Target Sales
Datetime
2021-12-01   Amy   1000  26000
2021-12-02   Amy   1000   0
...
2021-12-30   Amy   1000   0
2021-12-31   Amy   1000   0
2021-12-01   Zoe   1000  1680
2021-12-02   Zoe   1000   0
...
2021-12-30   Zoe   1000  19414
2021-12-31   Zoe   1000   0

I performed the following code, however, the result does not satisfy my need.

sum_dict = {'Target':'sum','Sales':'sum'}
df.groupby(['Name']).resample('W').apply(sum_dict )

And the result where the last index becomes Jan instead of Dec

            Name Target Sales
Datetime
2021-12-05   Amy   5000  35100
2021-12-12   Amy   7000  -8403.6
2021-12-19   Amy   7000  179176
2021-12-26   Amy   7000  50222
2022-01-02   Amy   5000  0
2021-12-05   Zoe   5000  1680
2021-12-12   Zoe   7000  57415
2021-12-19   Zoe   7000  80254
2021-12-26   Zoe   7000  75256.4
2022-01-02   Zoe   5000  43494

What I expect is the following:

            Name Target Sales
Datetime
2021-12-05   Amy   5000  35100
2021-12-12   Amy   7000  -8403.6
2021-12-19   Amy   7000  179176
2021-12-26   Amy   7000  50222
2021-12-31   Amy   5000  0
2021-12-05   Zoe   5000  1680
2021-12-12   Zoe   7000  57415
2021-12-19   Zoe   7000  80254
2021-12-26   Zoe   7000  75256.4
2021-12-31   Zoe   5000  43494

The end date is using the end date of that month instead of the last date of that week. Thanks!

Body:
Given the following dataframe:

import pandas as pd

df = pd.DataFrame(
    {
        "Datetime": {
            0: "2021-12-05",
            1: "2021-12-12",
            2: "2021-12-19",
            3: "2021-12-26",
            4: "2022-01-02",
            5: "2021-12-05",
            6: "2021-12-12",
            7: "2021-12-19",
            8: "2021-12-26",
            9: "2022-01-02",
        },
        "Name": {
            0: "Amy",
            1: "Amy",
            2: "Amy",
            3: "Amy",
            4: "Amy",
            5: "Zoe",
            6: "Zoe",
            7: "Zoe",
            8: "Zoe",
            9: "Zoe",
        },
        "Target": {
            0: 5000,
            1: 7000,
            2: 7000,
            3: 7000,
            4: 5000,
            5: 5000,
            6: 7000,
            7: 7000,
            8: 7000,
            9: 5000,
        },
        "Sales": {
            0: 35100.0,
            1: -8403.6,
            2: 179176.0,
            3: 50222.0,
            4: 0.0,
            5: 1680.0,
            6: 57415.0,
            7: 80254.0,
            8: 75256.4,
            9: 43494.0,
        },
    }
)

You could try like this:

from pandas.tseries.offsets import MonthEnd

# Convert "Datetime" column to pandas datetime objects
df["Datetime"] = pd.to_datetime(df["Datetime"], format="%Y-%m-%d")

# Find the dates to modify
mask = df["Datetime"].dt.month - df["Datetime"].shift(periods=1).dt.month < 0

# Apply date shift
df.loc[mask, "Datetime"] = df.loc[mask, "Datetime"].apply(lambda x: x - MonthEnd(1))

And so here the expected output:

print(df)
# Output
    Datetime Name  Target     Sales
0 2021-12-05  Amy    5000   35100.0
1 2021-12-12  Amy    7000   -8403.6
2 2021-12-19  Amy    7000  179176.0
3 2021-12-26  Amy    7000   50222.0
4 2021-12-31  Amy    5000       0.0
5 2021-12-05  Zoe    5000    1680.0
6 2021-12-12  Zoe    7000   57415.0
7 2021-12-19  Zoe    7000   80254.0
8 2021-12-26  Zoe    7000   75256.4
9 2021-12-31  Zoe    5000   43494.0


问:
PHP contact form keep input fields if error, otherwise clear
I want my contact form input fields to save the user's inputs if there's an error, otherwise have them cleared if the email goes through. Right now it works except when the email is sent the fields are still filled in. I could refresh the page but then it doesn't show the 'Your email has been sent' message.

Here's my form:

```<code><form class="contact-form" action="" method="post">
<input type="text" name="name" value="<?php if(isset($_POST["name"])) echo $_POST["name"]; ?>" />
</form>
</code>```

I tried adding something to my php code that handles the email business - if the message was sent, unset($_POST["name"]), and also adding to this form input's php else echo ''; but that didn't seem to work. It seems the variable was still set.

答:
Let's assume that your page is contact.php.

You php code should be something like this:

```<code>// we will keep here error message
$error = '';

// if request is get and isset sent
if ($_SERVER["REQUEST_METHOD"] === "GET" and isset($_GET["sent"]))
    echo '<p id="output-area">Message has been sent.</p>';
else {
    // if request is post
    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        // then verify input data
        if (!empty($_POST['msg'])) {
            // if mail was sent, redirect to contact.php?sent
            if (mail("someone@example.com", "My subject", $_POST['msg'])){
                header('Location: contact.php?sent');
                exit;
            } else
                $error = "Mail does not sent.";
        } else
            $error = 'Please fill in all inputs.';
    }
}

if ($error != '')
   echo '<p class="error">Error: ' . $error . '</p>';

// here goes your form
echo '<form class="contact-form" action="contact.php" method="post">
    <textarea name="msg">' . (!empty($_POST["msg"]) ? $_POST["msg"] : '') . '</textarea>
    <input type="submit" value="send">
</form>';
</code>```

Body:
I want my contact form input fields to save the user's inputs if there's an error, otherwise have them cleared if the email goes through. Right now it works except when the email is sent the fields are still filled in. I could refresh the page but then it doesn't show the 'Your email has been sent' message.

Here's my form:

<form class="contact-form" action="" method="post">
<input type="text" name="name" value="<?php if(isset($_POST["name"])) echo $_POST["name"]; ?>" />
</form>

I tried adding something to my php code that handles the email business - if the message was sent, unset($_POST["name"]), and also adding to this form input's php else echo ''; but that didn't seem to work. It seems the variable was still set.

Body:
Let's assume that your page is contact.php.

You php code should be something like this:

// we will keep here error message
$error = '';

// if request is get and isset sent
if ($_SERVER["REQUEST_METHOD"] === "GET" and isset($_GET["sent"]))
    echo '<p id="output-area">Message has been sent.</p>';
else {
    // if request is post
    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        // then verify input data
        if (!empty($_POST['msg'])) {
            // if mail was sent, redirect to contact.php?sent
            if (mail("someone@example.com", "My subject", $_POST['msg'])){
                header('Location: contact.php?sent');
                exit;
            } else
                $error = "Mail does not sent.";
        } else
            $error = 'Please fill in all inputs.';
    }
}

if ($error != '')
   echo '<p class="error">Error: ' . $error . '</p>';

// here goes your form
echo '<form class="contact-form" action="contact.php" method="post">
    <textarea name="msg">' . (!empty($_POST["msg"]) ? $_POST["msg"] : '') . '</textarea>
    <input type="submit" value="send">
</form>';


问:
Python/Pandas: Repeat row value for each row in column when multiple conditions are met
I have used pd.wide_to_long() to create a longer df.
I want to create a new column called "Bodyweight" that takes the value from the "Load" column when the exercise == "bodyweight" and displays it for each row entry for an athlete on that date.
the current layout is:

ie

Input

```<code>        Date    Player_Name Exercise    Set Reps    Load
0   Day 1   Player 1    Bench Press 1   5   120
1   Day 1   Player 1    Bench Press 2   5   120
2   Day 1   Player 1    Bench Press 3   5   120
3   Day 1   Player 1    Bodyweight  1   1   100
4   Day 2   Player 1    Squat   1   5   180
5   Day 2   Player 1    Squat   2   5   180
6   Day 2   Player 1    Squat   3   5   180
7   Day 2   Player 1    Bodyweight  1   1   101.5
8   Day 1   Player 2    Chin up 1   3   125
9   Day 1   Player 2    Bodyweight  1   1   92
</code>```

Output

```<code>Date    Player_Name Bodyweight  Exercise    Set Reps    Load
0   Day 1   Player 1    100 Bench Press 1   5   120
1   Day 1   Player 1    100 Bench Press 2   5   120
2   Day 1   Player 1    100 Bench Press 3   5   120
3   Day 2   Player 1    101.5   Squat   1   5   180
4   Day 2   Player 1    101.5   Squat   2   5   180
5   Day 2   Player 1    101.5   Squat   3   5   180
6   Day 1   Player 2    92  Chin up 1   3   125
</code>```

I have tried:

```<code>df["Body_Weight"] = df[df["Exercise"] == "Body Weight"]["Load"]
</code>```

to create a new column but this does not repeat the value for each entry of that player on that date.

Any help would be great!
Thanks,
Liam

答:
```<code># Create an empty dict for the player's bodyweights
bodyweight_dict={}

# Iterate through each entry in column "Exercise"
for idx, entry in enumerate(df["Exercise"]):
    # Check if the entry is equal to "Bodyweight"
    if entry == "Bodyweight":
        # If true, we will add the player's weight as a value to the player's name as a key
        bodyweight_dict[f'{df["Player_Name"][idx]}'] = df["Load"][idx]
    else:
        # If false, we will continue the for loop
        continue

# Iterate through each entry in column "Player_Name"
for idx, entry in enumerate(df["Player_Name"]):
    # Assign the stored bodyweights to each row in the dataframe
    df.loc[idx, "Bodyweight"] = bodyweight_dict[entry]
</code>```

Body:
I have used pd.wide_to_long() to create a longer df.
I want to create a new column called "Bodyweight" that takes the value from the "Load" column when the exercise == "bodyweight" and displays it for each row entry for an athlete on that date.
the current layout is:

ie

Input

        Date    Player_Name Exercise    Set Reps    Load
0   Day 1   Player 1    Bench Press 1   5   120
1   Day 1   Player 1    Bench Press 2   5   120
2   Day 1   Player 1    Bench Press 3   5   120
3   Day 1   Player 1    Bodyweight  1   1   100
4   Day 2   Player 1    Squat   1   5   180
5   Day 2   Player 1    Squat   2   5   180
6   Day 2   Player 1    Squat   3   5   180
7   Day 2   Player 1    Bodyweight  1   1   101.5
8   Day 1   Player 2    Chin up 1   3   125
9   Day 1   Player 2    Bodyweight  1   1   92

Output

Date    Player_Name Bodyweight  Exercise    Set Reps    Load
0   Day 1   Player 1    100 Bench Press 1   5   120
1   Day 1   Player 1    100 Bench Press 2   5   120
2   Day 1   Player 1    100 Bench Press 3   5   120
3   Day 2   Player 1    101.5   Squat   1   5   180
4   Day 2   Player 1    101.5   Squat   2   5   180
5   Day 2   Player 1    101.5   Squat   3   5   180
6   Day 1   Player 2    92  Chin up 1   3   125

I have tried:

df["Body_Weight"] = df[df["Exercise"] == "Body Weight"]["Load"]

to create a new column but this does not repeat the value for each entry of that player on that date.

Any help would be great!
Thanks,
Liam


问:
VS Code c++ debugger jumps over class functions instead of stepping into
I have a Class for an ADT which is organized into a .h header file and .cpp implementation file.

I'm attempting to test the class and I need the debugger to step into one of the class functions inside the .cpp implementation file. However, whenever I press step into the debugger just jumps over the function. I've tried to look for solutions but only find them from Visual Studio. Keep in mind that I am using Visual Studio Code! turning off "just my code" is not an option for me.

How can I make the debugger step into the functions inside my .h/.cpp files for my class? Thanks!

答: Question has been resolved in the comments. Since I have a lengthy makeFile, I forgot to add the debugging option when compiling my ADT files.</p>


问:
Remove and change className onClick for multiple elements simultaneously - ReactJS
I am currently trying to display several buttons based on array values. Out of those buttons, one will have a different className to the others and I want to switch this className to the button that's clicked.

In my codesandbox example, "John" has className value of "one". I want to be able to click on another button, giving it the className of "one" and giving John (or any other element that had the initial className of one) className="two"

Here's a codesandbox, hopefully that makes more sense.

答:
create a state:

```<code>const [activeName, setActiveName] = useState("");
</code>```

then when someone CLICK the element put onClick event:

```<code>onClick={() => setActiveName("invest")}
</code>```

Now set up a Class Rule,   if    activeName === 'invest' && 'classYouWantToApply'

like this:

```<code><div className={`${activeName === "invest" && "active"}`}>Invest</div>
</code>```

So here if  my State matches  the 'invest' which is the name of the element, then class 'active' applies, if the state does NOT match, then nothing happens.

This way ONLY 1 element that matches the state will have applied class, the rest will not.

I am assuming you are doing this for a NAV BAR, so that when user clicks a NAV Element, it  lights up, so user can see in Which Nav Element he is browsing. So this is the solution.

Body:
create a state:

const [activeName, setActiveName] = useState("");

then when someone CLICK the element put onClick event:

onClick={() => setActiveName("invest")}

Now set up a Class Rule,   if    activeName === 'invest' && 'classYouWantToApply'

like this:

<div className={`${activeName === "invest" && "active"}`}>Invest</div>

So here if  my State matches  the 'invest' which is the name of the element, then class 'active' applies, if the state does NOT match, then nothing happens.

This way ONLY 1 element that matches the state will have applied class, the rest will not.

I am assuming you are doing this for a NAV BAR, so that when user clicks a NAV Element, it  lights up, so user can see in Which Nav Element he is browsing. So this is the solution.


问:
ManyToOne Lazy loading not working Spring boot
I have make the rest api using Spring boot. It has two entities employee and department. Employee has department object so relation is ManyToOne. It is unidirectional. Department do not have the employees list. When I hit the employees GET method endpoint I am getting com.fasterxml.jackson.databind.exc.InvalidDefinitionException Exception. Please tell me how to solve it.

Employee Class:

```<code>@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String firstName;
private String lastName;
private Integer salary;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="department_id",referencedColumnName = "id",nullable = false)
private Department department;
</code>```

Department Class:

```<code>@Entity
@Table(name = "departments")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
</code>```

Employee Service:

```<code>@Service
public class EmployeeService {

private final EmployeeRepository employeeRepository;

@Autowired
public EmployeeService(EmployeeRepository employeeRepository) {
    this.employeeRepository = employeeRepository;
}

public List<Employee> getAllEmployees(){
    return employeeRepository.findAll();
}

public Employee getEmployeeById(Integer id){
    Optional<Employee> optionalEmployee = employeeRepository.findById(id);
    if(optionalEmployee.isEmpty()){
        throw new IllegalStateException("Department does not exists");
    }
    return optionalEmployee.get();
}

public Employee createEmployee(Employee employee){
    return employeeRepository.save(employee);
}
</code>```

Employee Controller:

```<code>@RestController
@RequestMapping(path = "/employees")
public class EmployeeController {

private final EmployeeService employeeService;

@Autowired
public EmployeeController(EmployeeService employeeService) {
    this.employeeService = employeeService;
}

@GetMapping
public List<Employee> getAllDepartments(){
    return employeeService.getAllEmployees();
}
   @PostMapping
public Employee createEmployee(@RequestBody Employee employee){
    return employeeService.createEmployee(employee);
}}
</code>```

答: You have to put @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) annotation in ManyToOne relationship mapping

Body:
I have make the rest api using Spring boot. It has two entities employee and department. Employee has department object so relation is ManyToOne. It is unidirectional. Department do not have the employees list. When I hit the employees GET method endpoint I am getting com.fasterxml.jackson.databind.exc.InvalidDefinitionException Exception. Please tell me how to solve it.

Employee Class:

@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String firstName;
private String lastName;
private Integer salary;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="department_id",referencedColumnName = "id",nullable = false)
private Department department;

Department Class:

@Entity
@Table(name = "departments")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;

Employee Service:

@Service
public class EmployeeService {

private final EmployeeRepository employeeRepository;

@Autowired
public EmployeeService(EmployeeRepository employeeRepository) {
    this.employeeRepository = employeeRepository;
}

public List<Employee> getAllEmployees(){
    return employeeRepository.findAll();
}

public Employee getEmployeeById(Integer id){
    Optional<Employee> optionalEmployee = employeeRepository.findById(id);
    if(optionalEmployee.isEmpty()){
        throw new IllegalStateException("Department does not exists");
    }
    return optionalEmployee.get();
}

public Employee createEmployee(Employee employee){
    return employeeRepository.save(employee);
}

Employee Controller:

@RestController
@RequestMapping(path = "/employees")
public class EmployeeController {

private final EmployeeService employeeService;

@Autowired
public EmployeeController(EmployeeService employeeService) {
    this.employeeService = employeeService;
}

@GetMapping
public List<Employee> getAllDepartments(){
    return employeeService.getAllEmployees();
}
   @PostMapping
public Employee createEmployee(@RequestBody Employee employee){
    return employeeService.createEmployee(employee);
}}


问:
Creating a StumbleUpon-like toolbar for Chrome
How can I get to do this? I've read the documentation but I find I can only have icon, a tooltip, a badge, and a popup. And I want to make it a StumbleUpon-like toolbar. Then I thought about using ContentScripts but I don't know where to add the html to inject because according to the documentation I only have the options of js or css. What am I missing here?

I have a js file:

```<code>$("body").before('<div name="extension-top" id="extension-top"></div>');
var top = document.getElementById("extension-top");
document.getElementsByTagName('body')[0].style.marginTop = '40px';
top.src = chrome.extension.getURL("popup.html");
</code>```

and css:

```<code>#extension-top { width:100%; height:40px; top:0; left:0; background:#000;margin:0;padding:0;}
</code>```

finally an html:

```<code><body id="extension-content">
    HELLO
</body>
</code>```

The bar shows up but the "hello" isn't anywhere to be seen =/

答:
There is an experimental Infobar API that you could use to make a StumbleUpon-like toolbar. See Infobars for documentation and examples.

Note that you won't be able to publish the extension to the Chrome Web Store until the API becomes stable.

Body:
How can I get to do this? I've read the documentation but I find I can only have icon, a tooltip, a badge, and a popup. And I want to make it a StumbleUpon-like toolbar. Then I thought about using ContentScripts but I don't know where to add the html to inject because according to the documentation I only have the options of js or css. What am I missing here?

I have a js file:

$("body").before('

');
var top = document.getElementById("extension-top");
document.getElementsByTagName('body')[0].style.marginTop = '40px';
top.src = chrome.extension.getURL("popup.html");

and css:

#extension-top { width:100%; height:40px; top:0; left:0; background:#000;margin:0;padding:0;}

finally an html:

    HELLO

The bar shows up but the "hello" isn't anywhere to be seen =/


问:
(Python)Unable to import excel file using colab
i have tried to import an excel csv file from my local disk but failed

```<code>import pandas as pd
df=pd.read_csv(r'C:/Users/Username/Desktop/da/SeoulBikeData.csv',encoding="gbk")
print("df")
</code>```

error:

```<code>FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/Username/Desktop/da/SeoulBikeData.csv'
</code>```

答:
Try uploading files on drive first. Then read. Go to file. Copy path. Try following code according to  mu method in then below

```<code>from google.colab import drive
drive.mount('/content/drive')
</code>```

after that:

```<code>df= pd.read_csv("copy path file here")
</code>```

Body:
i have tried to import an excel csv file from my local disk but failed

import pandas as pd
df=pd.read_csv(r'C:/Users/Username/Desktop/da/SeoulBikeData.csv',encoding="gbk")
print("df")

error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/Username/Desktop/da/SeoulBikeData.csv'

Body:
Try uploading files on drive first. Then read. Go to file. Copy path. Try following code according to  mu method in then below

from google.colab import drive
drive.mount('/content/drive')

after that:

df= pd.read_csv("copy path file here")


问:
Why can't C++ locals captured by reference be accessed through the stack pointer?
I noticed that compilers implement capture by reference by making an array on the stack of pointers to the captured locals, which can be passed to the lambda to access them. That surprised me because the compiler knows where the locals are relative to the stack pointer, so I thought it could just pass the stack pointer. That would make one less indirection in the lambda and save the work of putting the pointers on the stack. I was wondering why the compiler can't do that?

For example, this C++:

```<code>#include <functional>
extern void test(std::function<void()>& f);
int test2(int x, int y)
{
    std::function<void()> f([&]() { x += y; });
    test(f);
    return x;
}
</code>```

generates this assembly on Clang 13 -O3 (comments mine):

```<code>mov     dword ptr [rsp + 8], edi    // put x on the stack
mov     dword ptr [rsp + 12], esi   // put y on the stack
lea     rax, [rsp + 8]
mov     qword ptr [rsp + 16], rax   // put &x on the stack
lea     rax, [rsp + 12]
mov     qword ptr [rsp + 24], rax   // put &y on the stack
mov     qword ptr [rsp + 40], offset std::_Function_handler<void (), test2(int, int)::$_0>::_M_invoke(std::_Any_data const&)
mov     qword ptr [rsp + 32], offset std::_Function_handler<void (), test2(int, int)::$_0>::_M_manager(std::_Any_data&, std::_Any_data const&, std::_Manager_operation)
lea     rdi, [rsp + 16]
call    test(std::function<void ()>&)
</code>```

and similar on GCC and MSVC.

答:
What you see is not the non optimized lambda, but all the stuff around std::function.

If you simplify your code to:

```<code>template < typename F>
void test(F& f )
{
    f();
}

int test2(int x, int y)
{
    auto f=[&]() { x += y; };
    test(f);
    return x;
}

int main()
{
    return test2(1,2);
}
</code>```

The assembly becomes

```<code>test2(int, int):
        lea     eax, [rdi+rsi]
        ret
main:
        mov     eax, 3
        ret
</code>```

Which is fully optimized out all the stuff and propagate the result as constant.

The the difference: without std::function vs with std::function

Body:
I noticed that compilers implement capture by reference by making an array on the stack of pointers to the captured locals, which can be passed to the lambda to access them. That surprised me because the compiler knows where the locals are relative to the stack pointer, so I thought it could just pass the stack pointer. That would make one less indirection in the lambda and save the work of putting the pointers on the stack. I was wondering why the compiler can't do that?

For example, this C++:

#include <functional>
extern void test(std::function<void()>& f);
int test2(int x, int y)
{
    std::function<void()> f([&]() { x += y; });
    test(f);
    return x;
}

generates this assembly on Clang 13 -O3 (comments mine):

mov     dword ptr [rsp + 8], edi    // put x on the stack
mov     dword ptr [rsp + 12], esi   // put y on the stack
lea     rax, [rsp + 8]
mov     qword ptr [rsp + 16], rax   // put &x on the stack
lea     rax, [rsp + 12]
mov     qword ptr [rsp + 24], rax   // put &y on the stack
mov     qword ptr [rsp + 40], offset std::_Function_handler<void (), test2(int, int)::$_0>::_M_invoke(std::_Any_data const&)
mov     qword ptr [rsp + 32], offset std::_Function_handler<void (), test2(int, int)::$_0>::_M_manager(std::_Any_data&, std::_Any_data const&, std::_Manager_operation)
lea     rdi, [rsp + 16]
call    test(std::function<void ()>&)

and similar on GCC and MSVC.

Body:
What you see is not the non optimized lambda, but all the stuff around std::function.

If you simplify your code to:

template < typename F>
void test(F& f )
{
    f();
}

int test2(int x, int y)
{
    auto f=[&]() { x += y; };
    test(f);
    return x;
}

int main()
{
    return test2(1,2);
}

The assembly becomes

test2(int, int):
        lea     eax, [rdi+rsi]
        ret
main:
        mov     eax, 3
        ret

Which is fully optimized out all the stuff and propagate the result as constant.

The the difference: without std::function vs with std::function


问:
Convenient C++ struct initialisation
I'm trying to find a convenient way to initialise 'pod' C++ structs. Now, consider the following struct:

```<code>struct FooBar {
  int foo;
  float bar;
};
// just to make all examples work in C and C++:
typedef struct FooBar FooBar;
</code>```

If I want to conveniently initialise this in C (!), I could simply write:

```<code>/* A */ FooBar fb = { .foo = 12, .bar = 3.4 }; // illegal C++, legal C
</code>```

Note that I want to explicitly avoid the following notation, because it strikes me as being made to break my neck if I change anything in the struct in the future:

```<code>/* B */ FooBar fb = { 12, 3.4 }; // legal C++, legal C, bad style?
</code>```

To achieve the same (or at least similar) in C++ as in the /* A */ example, I would have to implement an annoying constructor:

```<code>FooBar::FooBar(int foo, float bar) : foo(foo), bar(bar) {}
// ->
/* C */ FooBar fb(12, 3.4);
</code>```

Which feels redundant and unnecessary. Also, it is pretty much as bad as the /* B */ example, as it does not explicitly state which value goes to which member.

So, my question is basically how I can achieve something similar to /* A */ or better in C++?
Alternatively, I would be okay with an explanation why I should not want to do this (i.e. why my mental paradigm is bad).

EDIT

By convenient, I mean also maintainable and non-redundant.

答:
I personally have found that using constructor with struct is the most pragmatic way to ensure struct members are initialized in code to sensible values.

As you say above, small downside is that one does not immediatelly see what param is which member, but most IDEs help here, if one hovers over the code.

What I consider more likely is that new member is added and in this case i want all constructions of the struct to fail to compile,  so developer is forced to review. In our fairly large code base, this has proven itself, because it guides developer in what needs attention and therefore creates self-maintained code.

Title: Convenient C++ struct initialisation

Body:
I'm trying to find a convenient way to initialise 'pod' C++ structs. Now, consider the following struct:

struct FooBar {
  int foo;
  float bar;
};
// just to make all examples work in C and C++:
typedef struct FooBar FooBar;

If I want to conveniently initialise this in C (!), I could simply write:

/* A */ FooBar fb = { .foo = 12, .bar = 3.4 }; // illegal C++, legal C

Note that I want to explicitly avoid the following notation, because it strikes me as being made to break my neck if I change anything in the struct in the future:

/* B */ FooBar fb = { 12, 3.4 }; // legal C++, legal C, bad style?

To achieve the same (or at least similar) in C++ as in the /* A */ example, I would have to implement an annoying constructor:

FooBar::FooBar(int foo, float bar) : foo(foo), bar(bar) {}
// ->
/* C */ FooBar fb(12, 3.4);

Which feels redundant and unnecessary. Also, it is pretty much as bad as the /* B */ example, as it does not explicitly state which value goes to which member.

So, my question is basically how I can achieve something similar to /* A */ or better in C++?
Alternatively, I would be okay with an explanation why I should not want to do this (i.e. why my mental paradigm is bad).

EDIT

By convenient, I mean also maintainable and non-redundant.