问:
Dome Image Projection
Im trying to create a GLSL fragment shader which projects an image to a dome. The input would be a sampler2D texture, an elevation and an azimuth.

The result should look like the following gif's.

Elevation between 0 and 90 degree (in this gif its between -90 and 90)

.

Azimuth between 0 and 360 degree

.

Right now my code looks like this:

```<code>#ifdef GL_ES
precision mediump float;
#endif

uniform float u_time;
uniform vec2 u_resolution;
uniform sampler2D u_texture_0;
uniform sampler2D u_texture_1;

// INPUT
const float azimuth=0.;// clockwise 360 degree
const float altitude=90.;// 0-90 dregree -> 90 = center
const float scale=1.;

// CALC
const float PI=3.14159265359;
const float azimuthRad=azimuth*PI/180.;
const float altitudeNormalization=sin((1.-(altitude/90.)));

float box(in vec2 _st,in vec2 _size){
    _size=vec2(.5)-_size*.5;
    vec2 uv=smoothstep(_size,_size+vec2(.001),_st);
    uv*=smoothstep(_size,_size+vec2(.001),vec2(1.)-_st);
    return uv.x*uv.y;
}

mat2 rotate(float angle){
    return mat2(cos(angle),-sin(angle),sin(angle),cos(angle));
}

void main(){
    vec2 st=gl_FragCoord.xy/u_resolution;
    vec4 color = texture2D(u_texture_1,st); // set background grid

    vec2 vPos=st;

    float aperture=180.;
    float apertureHalf=.5*aperture*(PI/180.);
    float maxFactor=sin(apertureHalf);

    // to unit sphere -> -1 - 1
    vPos=vec2(2.*vPos-1.);

    float l=length(vPos);
    if(l<=1.){
        float x=maxFactor*vPos.x;
        float y=maxFactor*vPos.y;
        float n=length(vec2(x,y));
        float z=sqrt(1.-n*n);
        float r=atan(n,z)/PI;
        float phi=atan(y,x);
        float u=r*cos(phi)+.5;
        float v=r*sin(phi)+.5;
        vec2 uv=vec2(u,v);

        // translate
        vec2 translate=vec2(sin(azimuthRad),cos(azimuthRad));
        uv+=translate*altitudeNormalization;

        // rotate
        uv-=.5;
        uv=rotate(PI-azimuthRad)*uv;
        uv+=.5;

        // scale
        float size=.5*scale;

        float box=box(uv,vec2(.5*size));

        uv.x*=-1.;
        uv.y*=-1.;

        if(box>=.1){
            vec3 b=vec3(box);
            //    gl_FragColor=vec4(b,1.);
            //uv *= box;
            color += texture2D(u_texture_0,uv);
        }
        gl_FragColor= color;

    }

}
</code>```

As you can see there are two things wrong, the texture is only displayed partially (I know that I kind of cut it out which is for sure wrong) and the distortion is also wrong. Any help would be apretiated.

答:
The issue is, that you use a scaled uv coordinates for the box test:

float size=.5*scale;

float box=box(uv,vec2(.5*size));
```
</blockquote>

<p>You have to consider this scale when you do the texture look up the texture. Furthermore you wrongly add 0.5 to the uv coordinates:</p>

<blockquote>
  <pre class="lang-c prettyprint-override"><code>float u=r*cos(phi)+.5;
float v=r*sin(phi)+.5;
</code>```

Set up the uv coordinates in range [-1.0, 1.0]:

vec2 uv = vec2(r*cos(phi), r*sin(phi));
```

<p>Translate, rotate and scale it (e.g. <code>const float scale = 8.0;</code>):</p>

<pre class="lang-c prettyprint-override"><code>// translate
vec2 translate = vec2(sin(azimuthRad), cos(azimuthRad));
uv += translate * altitudeNormalization;

// rotate
uv = rotate(PI-azimuthRad)*uv;

// scale
uv = uv * scale;
</code>```

Transform the uv coordinate from range [-1.0, 1.0] to [0.0, 1.0] and do a correct box test:

uv = uv * 0.5 + 0.5;

vec2 boxtest = step(0.0, uv) * step(uv, vec2(1.0));

if (boxtest.x * boxtest.y > 0.0)
    color += texture2D(u_texture_0, uv);
```

<p>Fragment shader main:</p>

<pre class="lang-c prettyprint-override"><code>void main(){
    vec2 st = gl_FragCoord.xy/u_resolution;
    vec4 color = texture2D(u_texture_1,st); // set background grid

    float aperture=180.;
    float apertureHalf=.5*aperture*(PI/180.);
    float maxFactor=sin(apertureHalf);

    // to unit sphere -> -1 - 1
    vec2 vPos = st * 2.0 - 1.0;

    float l=length(vPos);
    if(l<=1.){
        float x = maxFactor*vPos.x;
        float y = maxFactor*vPos.y;
        float n = length(vec2(x,y));
        float z = sqrt(1.-n*n);
        float r = atan(n,z)/PI;
        float phi = atan(y,x);
        float u = r*cos(phi);
        float v = r*sin(phi);
        vec2 uv = vec2(r*cos(phi), r*sin(phi));

        // translate
        vec2 translate = vec2(sin(azimuthRad), cos(azimuthRad));
        uv += translate * altitudeNormalization;

        // rotate
        uv = rotate(PI-azimuthRad)*uv;

        // scale
        uv = uv * scale;

        uv = uv * 0.5 + 0.5;

        vec2 boxtest = step(0.0, uv) * step(uv, vec2(1.0));

        if (boxtest.x * boxtest.y > 0.0)
            color += texture2D(u_texture_0, uv);
    }

    gl_FragColor = color;
}
</code>```

Title: Dome Image Projection

Body:
Im trying to create a GLSL fragment shader which projects an image to a dome. The input would be a sampler2D texture, an elevation and an azimuth.

The result should look like the following gif's.

Elevation between 0 and 90 degree (in this gif its between -90 and 90)

.

Azimuth between 0 and 360 degree

.

Right now my code looks like this:

#ifdef GL_ES
precision mediump float;
#endif

uniform float u_time;
uniform vec2 u_resolution;
uniform sampler2D u_texture_0;
uniform sampler2D u_texture_1;

// INPUT
const float azimuth=0.;// clockwise 360 degree
const float altitude=90.;// 0-90 dregree -> 90 = center
const float scale=1.;

// CALC
const float PI=3.14159265359;
const float azimuthRad=azimuth*PI/180.;
const float altitudeNormalization=sin((1.-(altitude/90.)));

float box(in vec2 _st,in vec2 _size){
    _size=vec2(.5)-_size*.5;
    vec2 uv=smoothstep(_size,_size+vec2(.001),_st);
    uv*=smoothstep(_size,_size+vec2(.001),vec2(1.)-_st);
    return uv.x*uv.y;
}

mat2 rotate(float angle){
    return mat2(cos(angle),-sin(angle),sin(angle),cos(angle));
}

void main(){
    vec2 st=gl_FragCoord.xy/u_resolution;
    vec4 color = texture2D(u_texture_1,st); // set background grid

    vec2 vPos=st;

    float aperture=180.;
    float apertureHalf=.5*aperture*(PI/180.);
    float maxFactor=sin(apertureHalf);

    // to unit sphere -> -1 - 1
    vPos=vec2(2.*vPos-1.);

    float l=length(vPos);
    if(l<=1.){
        float x=maxFactor*vPos.x;
        float y=maxFactor*vPos.y;
        float n=length(vec2(x,y));
        float z=sqrt(1.-n*n);
        float r=atan(n,z)/PI;
        float phi=atan(y,x);
        float u=r*cos(phi)+.5;
        float v=r*sin(phi)+.5;
        vec2 uv=vec2(u,v);

        // translate
        vec2 translate=vec2(sin(azimuthRad),cos(azimuthRad));
        uv+=translate*altitudeNormalization;

        // rotate
        uv-=.5;
        uv=rotate(PI-azimuthRad)*uv;
        uv+=.5;

        // scale
        float size=.5*scale;

        float box=box(uv,vec2(.5*size));

        uv.x*=-1.;
        uv.y*=-1.;

        if(box>=.1){
            vec3 b=vec3(box);
            //    gl_FragColor=vec4(b,1.);
            //uv *= box;
            color += texture2D(u_texture_0,uv);
        }
        gl_FragColor= color;

    }

}

As you can see there are two things wrong, the texture is only displayed partially (I know that I kind of cut it out which is for sure wrong) and the distortion is also wrong. Any help would be apretiated.

Body:
The issue is, that you use a scaled uv coordinates for the box test:

float size=.5*scale;

float box=box(uv,vec2(.5*size));

You have to consider this scale when you do the texture look up the texture. Furthermore you wrongly add 0.5 to the uv coordinates:

float u=r*cos(phi)+.5;
float v=r*sin(phi)+.5;

Set up the uv coordinates in range [-1.0, 1.0]:

vec2 uv = vec2(r*cos(phi), r*sin(phi));

Translate, rotate and scale it (e.g. const float scale = 8.0;):

// translate
vec2 translate = vec2(sin(azimuthRad), cos(azimuthRad));
uv += translate * altitudeNormalization;

// rotate
uv = rotate(PI-azimuthRad)*uv;

// scale
uv = uv * scale;

Transform the uv coordinate from range [-1.0, 1.0] to [0.0, 1.0] and do a correct box test:

uv = uv * 0.5 + 0.5;

vec2 boxtest = step(0.0, uv) * step(uv, vec2(1.0));

if (boxtest.x * boxtest.y > 0.0)
    color += texture2D(u_texture_0, uv);

Fragment shader main:

void main(){
    vec2 st = gl_FragCoord.xy/u_resolution;
    vec4 color = texture2D(u_texture_1,st); // set background grid

    float aperture=180.;
    float apertureHalf=.5*aperture*(PI/180.);
    float maxFactor=sin(apertureHalf);

    // to unit sphere -> -1 - 1
    vec2 vPos = st * 2.0 - 1.0;

    float l=length(vPos);
    if(l<=1.){
        float x = maxFactor*vPos.x;
        float y = maxFactor*vPos.y;
        float n = length(vec2(x,y));
        float z = sqrt(1.-n*n);
        float r = atan(n,z)/PI;
        float phi = atan(y,x);
        float u = r*cos(phi);
        float v = r*sin(phi);
        vec2 uv = vec2(r*cos(phi), r*sin(phi));

        // translate
        vec2 translate = vec2(sin(azimuthRad), cos(azimuthRad));
        uv += translate * altitudeNormalization;

        // rotate
        uv = rotate(PI-azimuthRad)*uv;

        // scale
        uv = uv * scale;

        uv = uv * 0.5 + 0.5;

        vec2 boxtest = step(0.0, uv) * step(uv, vec2(1.0));

        if (boxtest.x * boxtest.y > 0.0)
            color += texture2D(u_texture_0, uv);
    }

    gl_FragColor = color;
}


来源: stackexchange

问:
Create a new column based on date time and today's date in pandas
I have a dataframe as shown below

```<code>ID      Start_Date
1       2018-07-23
2       2019-07-14
3       2020-07-23
4       2018-07-20
5       2020-02-23
6       2018-07-23
</code>```

From the above, I would like to flag False if start_Date is after today's date.

Expected Output:

```<code>ID      Start_Date       Start_Date_Flag
1       2018-07-23       True
2       2019-07-14       True
3       2020-07-23       False
4       2018-07-20       True
5       2020-02-23       False
6       2018-07-23       True
</code>```

答:
Use mask by Series.lt with today datetime:

```<code>df['Start_Date'] = pd.to_datetime(df['Start_Date'])

df['Start_Date_Flag'] = df['Start_Date'].lt(pd.to_datetime('now'))
print (df)
   ID Start_Date  Start_Date_Flag
0   1 2018-07-23             True
1   2 2019-07-14             True
2   3 2020-07-23            False
3   4 2018-07-20             True
4   5 2020-02-23            False
5   6 2018-07-23             True
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe as shown below

ID      Start_Date
1       2018-07-23
2       2019-07-14
3       2020-07-23
4       2018-07-20
5       2020-02-23
6       2018-07-23

From the above, I would like to flag False if start_Date is after today's date.

Expected Output:

ID      Start_Date       Start_Date_Flag
1       2018-07-23       True
2       2019-07-14       True
3       2020-07-23       False
4       2018-07-20       True
5       2020-02-23       False
6       2018-07-23       True

Body:
Use mask by Series.lt with today datetime:

df['Start_Date'] = pd.to_datetime(df['Start_Date'])

df['Start_Date_Flag'] = df['Start_Date'].lt(pd.to_datetime('now'))
print (df)
   ID Start_Date  Start_Date_Flag
0   1 2018-07-23             True
1   2 2019-07-14             True
2   3 2020-07-23            False
3   4 2018-07-20             True
4   5 2020-02-23            False
5   6 2018-07-23             True


问:
Flutter - How to style different color text for Flat Buttons depending on whether button is in appbar or main screen
In my styles.dart I have the following theme:

```<code>final ThemeData purpleTheme = ThemeData(
    brightness: Brightness.light,
    primaryColor: PURPLE,
    buttonColor: GREEN,
    fontFamily: FontNameDefault,
    buttonTheme: ButtonThemeData(
        textTheme: ButtonTextTheme
            .primary, // TODO: This is making the flat buttons all appear in blue instead of purple
        buttonColor: GREEN,
        height: 45),
    appBarTheme: AppBarTheme(
      textTheme: TextTheme(title: AppBarTextStyle, button: AppBarTextStyle),
      iconTheme: new IconThemeData(color: Colors.white),
      brightness: Brightness.dark,
      color: PURPLE,
    ),
    textTheme: TextTheme(
        title: TitleTextStyle,
        body1: Body1TextStyle,
        subtitle: SubtitleTextStyle));
</code>```

With the above theme setting, The buttonTheme textTheme is ButtonTextTheme.primary. The primary color seems to be blue for some reason, even though nowhewere in my styling do I use blue. When I add

```<code>colorScheme: ColorScheme.light().copyWith(primary: PURPLE)
</code>```

To the style, the primary color becomes purple. However, I would like the flat buttons in the purple appbar to use white text, and flat buttons in the white screen to use purple text. How can I get that coded into the ThemeData?

答:
The use case you have is already well defined in the Material theme spec.

Here I am going to explain how to style color of any widget (eg: button/ text/ customWidget..) depending on the parent widget color.

example use cases:

primary colored text on white colored appBar

white colored text on primary colored appBar

black color text on white color surface

primary color text on white color surface

Here you go.

Step 1:

First of all,
Define a primary color swatch that define all the variants from 50 to 900.

```<code>final MaterialColor lightPrimaryColorSwatch = MaterialColor(
    0xff4f9af0,
    {
      50: Color(0xffeaf3fd),
      100: Color(0xffcae1fb),
      200: Color(0xffa7cdf8),
      300: Color(0xff84b8f5),
      400: Color(0xff69a9f2),
      500: Color(0xff4f9af0),
      600: Color(0xff4892ee),
      700: Color(0xff3f88ec),
      800: Color(0xff367ee9),
      900: Color(0xff266ce5),
    },
  );
</code>```

Step 2:

You need to define a ColorScheme object that define all the 12 colors of material spec.

```<code>final ColorScheme lightColorScheme = ColorScheme(
        brightness: Brightness.light,
        primary: Color(0xff4f9af0),
        primaryVariant: Color(0xff2c86ed),
        secondary: Color(0xff0863c4),
        secondaryVariant: Color(0xff259b24),
        error: Color(0xffb00020),
        background: Color(0xfff7f8fa),
        onError: Colors.white,
        onSecondary: Colors.white,
        onBackground: Color(0xff292929),
        onPrimary: Colors.white,
        onSurface: Color(0xff292929),
        surface: Colors.white,
      );
</code>```

Step 3:

Define theme data for your MaterialApp using the above defined values.

```<code> return MaterialApp(

      theme: ThemeData(
        brightness: Brightness.light,
        primarySwatch: lightPrimaryColorSwatch,
        primaryColor: lightColorScheme.primary,
        primaryColorDark: lightColorScheme.primaryVariant,
        errorColor: lightColorScheme.error,
        colorScheme: lightColorScheme,
        primaryColorBrightness: Brightness.dark,
        accentColorBrightness: Brightness.dark,
        accentColor: lightColorScheme.secondary,
        primaryColorLight: lightColorScheme.secondaryVariant,
        backgroundColor: lightColorScheme.background,
        canvasColor: lightColorScheme.background,
      ),
    //... other attributes go here
  );
</code>```

Now you are all set. From now on, you can use those 12 colors for any type of combo that you wish.

Here is an example.

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final MaterialColor lightPrimaryColorSwatch = MaterialColor(
      0xff4f9af0,
      {
        50: Color(0xffeaf3fd),
        100: Color(0xffcae1fb),
        200: Color(0xffa7cdf8),
        300: Color(0xff84b8f5),
        400: Color(0xff69a9f2),
        500: Color(0xff4f9af0),
        600: Color(0xff4892ee),
        700: Color(0xff3f88ec),
        800: Color(0xff367ee9),
        900: Color(0xff266ce5),
      },
    );

    final ColorScheme lightColorScheme = ColorScheme(
      brightness: Brightness.light,
      primary: Color(0xff4f9af0),
      primaryVariant: Color(0xff2c86ed),
      secondary: Color(0xff0863c4),
      secondaryVariant: Color(0xff259b24),
      error: Color(0xffb00020),
      background: Color(0xfff7f8fa),
      onError: Colors.white,
      onSecondary: Colors.white,
      onBackground: Color(0xff292929),
      onPrimary: Colors.white,
      onSurface: Color(0xff292929),
      surface: Colors.white,
    );
    return MaterialApp(
      theme: ThemeData(
        brightness: Brightness.light,
        primarySwatch: lightPrimaryColorSwatch,
        primaryColor: lightColorScheme.primary,
        primaryColorDark: lightColorScheme.primaryVariant,
        errorColor: lightColorScheme.error,
        colorScheme: lightColorScheme,
        primaryColorBrightness: Brightness.dark,
        accentColorBrightness: Brightness.dark,
        accentColor: lightColorScheme.secondary,
        primaryColorLight: lightColorScheme.secondaryVariant,
        backgroundColor: lightColorScheme.background,
        canvasColor: lightColorScheme.background,
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

    class MyWidget extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Column(
          children: <Widget>[
            SizedBox(height: 8.0),
           ///white color text on container with primary color
            Container(
                color: Theme.of(context).colorScheme.primary,
                height: 40.0,
                width: 100.0,
                alignment: Alignment.center,
                child: Padding(
                  padding: EdgeInsets.all(8.0),
                  child: Text('Hello, World!',
                      style: Theme.of(context).textTheme.bodyText2.copyWith(
                          color: Theme.of(context).colorScheme.onPrimary)),
                )),
            SizedBox(height: 8.0),
            ///Primary color text on  white color container.
            Container(
                color: Theme.of(context).colorScheme.surface,
                height: 40.0,
                width: 100.0,
                alignment: Alignment.center,
                child: Padding(
                  padding: EdgeInsets.all(8.0),
                  child: Text('Hello, World!',
                      style: Theme.of(context)
                          .textTheme
                          .bodyText2
                          .copyWith(color: Theme.of(context).colorScheme.primary)),
                )),
          ],
        );
      }
    }
</code>```

You can find a live demo here.

Body:
In my styles.dart I have the following theme:

final ThemeData purpleTheme = ThemeData(
    brightness: Brightness.light,
    primaryColor: PURPLE,
    buttonColor: GREEN,
    fontFamily: FontNameDefault,
    buttonTheme: ButtonThemeData(
        textTheme: ButtonTextTheme
            .primary, // TODO: This is making the flat buttons all appear in blue instead of purple
        buttonColor: GREEN,
        height: 45),
    appBarTheme: AppBarTheme(
      textTheme: TextTheme(title: AppBarTextStyle, button: AppBarTextStyle),
      iconTheme: new IconThemeData(color: Colors.white),
      brightness: Brightness.dark,
      color: PURPLE,
    ),
    textTheme: TextTheme(
        title: TitleTextStyle,
        body1: Body1TextStyle,
        subtitle: SubtitleTextStyle));

With the above theme setting, The buttonTheme textTheme is ButtonTextTheme.primary. The primary color seems to be blue for some reason, even though nowhewere in my styling do I use blue. When I add

colorScheme: ColorScheme.light().copyWith(primary: PURPLE)

To the style, the primary color becomes purple. However, I would like the flat buttons in the purple appbar to use white text, and flat buttons in the white screen to use purple text. How can I get that coded into the ThemeData?

Body:
The use case you have is already well defined in the Material theme spec.

Here I am going to explain how to style color of any widget (eg: button/ text/ customWidget..) depending on the parent widget color.

example use cases:

primary colored text on white colored appBar

white colored text on primary colored appBar

black color text on white color surface

primary color text on white color surface

Here you go.

Step 1:

First of all,
Define a primary color swatch that define all the variants from 50 to 900.

final MaterialColor lightPrimaryColorSwatch = MaterialColor(
    0xff4f9af0,
    {
      50: Color(0xffeaf3fd),
      100: Color(0xffcae1fb),
      200: Color(0xffa7cdf8),
      300: Color(0xff84b8f5),
      400: Color(0xff69a9f2),
      500: Color(0xff4f9af0),
      600: Color(0xff4892ee),
      700: Color(0xff3f88ec),
      800: Color(0xff367ee9),
      900: Color(0xff266ce5),
    },
  );

Step 2:

You need to define a ColorScheme object that define all the 12 colors of material spec.

final ColorScheme lightColorScheme = ColorScheme(
        brightness: Brightness.light,
        primary: Color(0xff4f9af0),
        primaryVariant: Color(0xff2c86ed),
        secondary: Color(0xff0863c4),
        secondaryVariant: Color(0xff259b24),
        error: Color(0xffb00020),
        background: Color(0xfff7f8fa),
        onError: Colors.white,
        onSecondary: Colors.white,
        onBackground: Color(0xff292929),
        onPrimary: Colors.white,
        onSurface: Color(0xff292929),
        surface: Colors.white,
      );

Step 3:

Define theme data for your MaterialApp using the above defined values.

 return MaterialApp(

      theme: ThemeData(
        brightness: Brightness.light,
        primarySwatch: lightPrimaryColorSwatch,
        primaryColor: lightColorScheme.primary,
        primaryColorDark: lightColorScheme.primaryVariant,
        errorColor: lightColorScheme.error,
        colorScheme: lightColorScheme,
        primaryColorBrightness: Brightness.dark,
        accentColorBrightness: Brightness.dark,
        accentColor: lightColorScheme.secondary,
        primaryColorLight: lightColorScheme.secondaryVariant,
        backgroundColor: lightColorScheme.background,
        canvasColor: lightColorScheme.background,
      ),
    //... other attributes go here
  );

Now you are all set. From now on, you can use those 12 colors for any type of combo that you wish.

Here is an example.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final MaterialColor lightPrimaryColorSwatch = MaterialColor(
      0xff4f9af0,
      {
        50: Color(0xffeaf3fd),
        100: Color(0xffcae1fb),
        200: Color(0xffa7cdf8),
        300: Color(0xff84b8f5),
        400: Color(0xff69a9f2),
        500: Color(0xff4f9af0),
        600: Color(0xff4892ee),
        700: Color(0xff3f88ec),
        800: Color(0xff367ee9),
        900: Color(0xff266ce5),
      },
    );

    final ColorScheme lightColorScheme = ColorScheme(
      brightness: Brightness.light,
      primary: Color(0xff4f9af0),
      primaryVariant: Color(0xff2c86ed),
      secondary: Color(0xff0863c4),
      secondaryVariant: Color(0xff259b24),
      error: Color(0xffb00020),
      background: Color(0xfff7f8fa),
      onError: Colors.white,
      onSecondary: Colors.white,
      onBackground: Color(0xff292929),
      onPrimary: Colors.white,
      onSurface: Color(0xff292929),
      surface: Colors.white,
    );
    return MaterialApp(
      theme: ThemeData(
        brightness: Brightness.light,
        primarySwatch: lightPrimaryColorSwatch,
        primaryColor: lightColorScheme.primary,
        primaryColorDark: lightColorScheme.primaryVariant,
        errorColor: lightColorScheme.error,
        colorScheme: lightColorScheme,
        primaryColorBrightness: Brightness.dark,
        accentColorBrightness: Brightness.dark,
        accentColor: lightColorScheme.secondary,
        primaryColorLight: lightColorScheme.secondaryVariant,
        backgroundColor: lightColorScheme.background,
        canvasColor: lightColorScheme.background,
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

    class MyWidget extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Column(
          children: <Widget>[
            SizedBox(height: 8.0),
           ///white color text on container with primary color
            Container(
                color: Theme.of(context).colorScheme.primary,
                height: 40.0,
                width: 100.0,
                alignment: Alignment.center,
                child: Padding(
                  padding: EdgeInsets.all(8.0),
                  child: Text('Hello, World!',
                      style: Theme.of(context).textTheme.bodyText2.copyWith(
                          color: Theme.of(context).colorScheme.onPrimary)),
                )),
            SizedBox(height: 8.0),
            ///Primary color text on  white color container.
            Container(
                color: Theme.of(context).colorScheme.surface,
                height: 40.0,
                width: 100.0,
                alignment: Alignment.center,
                child: Padding(
                  padding: EdgeInsets.all(8.0),
                  child: Text('Hello, World!',
                      style: Theme.of(context)
                          .textTheme
                          .bodyText2
                          .copyWith(color: Theme.of(context).colorScheme.primary)),
                )),
          ],
        );
      }
    }

You can find a live demo here.


问:
Why is Node.js performance on Windows server significantly improved by running VSCode at the same time?
EDIT: Although I have not found an answer to the question, I have found a solution to the problem: use setImmediate() instead of setTimeout(). This has really speeded up execution without impacting the web server responsiveness. But the mystery of the behaviour of setTimeout() still remains unanswered, at least for now.

This is a Node.js performance question that is quite baffling to me.

I have set up a node.js web server application running on Windows 2012 R2, using only the built-in Node http library. I am not using any other Node libraries. To develop the app I use Remote Desktop Connection to log on to the server from a separate workstation on the same 1GB LAN, and then use Visual Studio Code on the server to edit the Node.js source code. The web server is run through a separate cmd window, using >node webserver.js

Apart from being a web server, the main purpose of the app is to carry out continuous calculations over many hours. The calculations are quite simple, but tedious, and are done in batches of around 2000, using a loop implemented by calling setTimeout( cycle_function, 1 ) at the end of each cycle, to fire up the next cycle. The loop is set up like this simply to allow the app to respond to incoming http requests without locking up.

Each execution of the cycle is called a tick, and a tick counter is maintained. A separate interval timer of 1000ms is set to run a small function that records how many cycles of calculations (ticks) were performed in the previous second, i.e. ticks per second. It does this by recording the tick count, and calculating the difference between the previous tick count and the current tick count each time it is run.

The up-to-date results of the calculations done so far can be viewed at any time in a web page. An XMLHttp request is sent from a script in an html page on my workstation to the server. The Node web server function responds with a JSON structure of results, sent back to the browser (about 250k). The report includes the tick count and the ticks per second stats, which are displayed in the browser. The browser also uses a timer loop to repeat the web page request every 100ms, to get the latest up-to-date information.

It runs smoothly and left to its own devices the cycle count reported on the web page reports around 80 cycles per second. I was somewhat puzzled that this is quite low, and I thought maybe the frequency of the web page requests was too high. However, the server CPU is not heavily loaded (<3%) and reducing the web page refresh frequency to 1/sec seems to have no effect on the cycle rate. Closing the web browser altogether has no effect either.

Now for the puzzle. If I log in to the server with Remote Desktop, open up VSCode (without opening any source files) move the mouse around on the VSCode window, then the calculation cycle rate speeds up significantly. It reliably goes from the background 80 cycles per second to peak at around 500 cycles per second. When I stop moving the mouse around, the cycle rate drops back to the steady 80 per second. Closing VSCode and moving the mouse around on the server desktop or any other Windows app (notepad, paint, etc) has no effect. It seems that only VSCode that has this impact.

Why is it that increasing the mouse activity in the VSCode window causes my completely separate Node application to speed up significantly?

Note: I thought that the activity in VSCode may be slowing down the interval at which the stats are being calculated - so if it was running every 6 secs instead of every second, then it would record a higher rate. However, the stats report is being updated in the web page every second, and the cycles per second changes every second too, so it is definitely being recalculated.

Here is some of the code:

The batch calculation cycle:

// ========================================================================================== T1
/**

This function is triggered on a Timeout timer to run a calculation cycle
*/
var forestTimeTickCount = 0;
var ticksPerSecond = 0;
var prevTickCount = 0;

function forestTimeTick(){

```<code> // increment the time tick count
 forestTimeTickCount++;
 if( forestTimeTickCount % 1000 == 0 ) log( "... tick " + forestTimeTickCount ) ;

 // update the plant calculations (batch of 2000)
 plants.timeTick(forestTimeTickCount);

 // if the clock is running, schedule the time for the next clock tick
 if( clockIsRunning ) setTimeout( forestTimeTick, 1 );
</code>```

}

// calculator for the ticks per second
function calcTPS(){
ticksPerSecond = forestTimeTickCount - prevTickCount;
prevTickCount = forestTimeTickCount;
}

// repeat the ticks per second calculation every second
setInterval( calcTPS, 1000 );

This is the Node.http web server creation:

//create a server object on port MainPort and listen for requests
try{

```<code> var MainPortServer = http.createServer( (req, res) =>{

     let dataString = "";
     req.on( "data", chunk => {
         let sChunk = chunk.toString( "utf8" );
         log( "MainPort Chunk: ", sChunk );
         dataString += sChunk;
     });

     req.on( "end", () => {
         let qParams = getAllRequestData( req , dataString );
         handlePortMainPortRequest( req, res, qParams );

     });

 });

 MainPortServer.on("error", err=>{
     console.error( err );
     log( ">>>>>>>>>>>>> TERMINATING")
     process.exit (1);
 });

 MainPortServer.listen( mainPort);
 log( "Web server [MainPort] listening on port " + mainPort )
</code>```

} catch(e) {
console.error( e );
log( ">>>>>>>>>>>>> TERMINATING")
process.exit (1);
}

This is the function that processes the web request:

function handlePortMainPortRequest (req, res, qParams ) {

```<code> if( !qParams.path || qParams.path.length == 0 ) { qParams.path = [ "reset" ] };

 switch( qParams.path[0] ){

     // This case handles a request for JSON structure of latest status
     case "pcl":

         // generate the JSON to be sent
         var pcl = plants.getPlantStatusList();

         // add the tick count and ticks per second stats
         pcl.push( { tick: forest.ticks(), tps: forest.tps() } );

         res.setHeader( "Content-type", "application/json" );
         res.end( JSON.stringify( pcl ) );
         return;

    //
    /// There are other cases here, not relevant to the question
    //

 }
</code>```

}

Web page clips

This shows the normal tick rate without MSCode running (tick rate 76/ps):

And this is a snapshot taken while moving the mouse around on MSCode in the server through remote desktop (tick rate 517/s):

答:
After a bit of further research, the answer to this question seems to lie in some anomaly in the timer handling, affecting the way in which Node.js interacts with the system timers.

I have transferred the application to a newer server, also Windows Server 2012 but different motherboard/CPU, and repeated the experiment.

On this server, running VSCode has no effect on the performance of the application. AFAIK, the only difference between the servers is that the slower one is a (somewhat aged) Fujitsu Intel XEON running on an AMI motherboard, whereas the faster is a locally-built Intel Core I7 running on an ASRock motherboard. The I7/ASRock combination runs the application around 3-5x faster than the Xeon.

My conjecture is that having VSCode running, and moving the mouse, causes multiple interrupts that cause Windows to short-cut the setTimout function in some way - maybe checking sooner for timer elapse than it would otherwise have done. But it's probably not worth the trouble to research that any further.

Thanks to Alexei Levenkov and JFriend for your comments.

Body:
EDIT: Although I have not found an answer to the question, I have found a solution to the problem: use setImmediate() instead of setTimeout(). This has really speeded up execution without impacting the web server responsiveness. But the mystery of the behaviour of setTimeout() still remains unanswered, at least for now.

This is a Node.js performance question that is quite baffling to me.

I have set up a node.js web server application running on Windows 2012 R2, using only the built-in Node http library. I am not using any other Node libraries. To develop the app I use Remote Desktop Connection to log on to the server from a separate workstation on the same 1GB LAN, and then use Visual Studio Code on the server to edit the Node.js source code. The web server is run through a separate cmd window, using >node webserver.js

Apart from being a web server, the main purpose of the app is to carry out continuous calculations over many hours. The calculations are quite simple, but tedious, and are done in batches of around 2000, using a loop implemented by calling setTimeout( cycle_function, 1 ) at the end of each cycle, to fire up the next cycle. The loop is set up like this simply to allow the app to respond to incoming http requests without locking up.

Each execution of the cycle is called a tick, and a tick counter is maintained. A separate interval timer of 1000ms is set to run a small function that records how many cycles of calculations (ticks) were performed in the previous second, i.e. ticks per second. It does this by recording the tick count, and calculating the difference between the previous tick count and the current tick count each time it is run.

The up-to-date results of the calculations done so far can be viewed at any time in a web page. An XMLHttp request is sent from a script in an html page on my workstation to the server. The Node web server function responds with a JSON structure of results, sent back to the browser (about 250k). The report includes the tick count and the ticks per second stats, which are displayed in the browser. The browser also uses a timer loop to repeat the web page request every 100ms, to get the latest up-to-date information.

It runs smoothly and left to its own devices the cycle count reported on the web page reports around 80 cycles per second. I was somewhat puzzled that this is quite low, and I thought maybe the frequency of the web page requests was too high. However, the server CPU is not heavily loaded (<3%) and reducing the web page refresh frequency to 1/sec seems to have no effect on the cycle rate. Closing the web browser altogether has no effect either.

Now for the puzzle. If I log in to the server with Remote Desktop, open up VSCode (without opening any source files) move the mouse around on the VSCode window, then the calculation cycle rate speeds up significantly. It reliably goes from the background 80 cycles per second to peak at around 500 cycles per second. When I stop moving the mouse around, the cycle rate drops back to the steady 80 per second. Closing VSCode and moving the mouse around on the server desktop or any other Windows app (notepad, paint, etc) has no effect. It seems that only VSCode that has this impact.

Why is it that increasing the mouse activity in the VSCode window causes my completely separate Node application to speed up significantly?

Note: I thought that the activity in VSCode may be slowing down the interval at which the stats are being calculated - so if it was running every 6 secs instead of every second, then it would record a higher rate. However, the stats report is being updated in the web page every second, and the cycles per second changes every second too, so it is definitely being recalculated.

Here is some of the code:

The batch calculation cycle:

// ========================================================================================== T1
/**

This function is triggered on a Timeout timer to run a calculation cycle
*/
var forestTimeTickCount = 0;
var ticksPerSecond = 0;
var prevTickCount = 0;

function forestTimeTick(){

 // increment the time tick count
 forestTimeTickCount++;
 if( forestTimeTickCount % 1000 == 0 ) log( "... tick " + forestTimeTickCount ) ;

 // update the plant calculations (batch of 2000)
 plants.timeTick(forestTimeTickCount);

 // if the clock is running, schedule the time for the next clock tick
 if( clockIsRunning ) setTimeout( forestTimeTick, 1 );

}

// calculator for the ticks per second
function calcTPS(){
ticksPerSecond = forestTimeTickCount - prevTickCount;
prevTickCount = forestTimeTickCount;
}

// repeat the ticks per second calculation every second
setInterval( calcTPS, 1000 );

This is the Node.http web server creation:

//create a server object on port MainPort and listen for requests
try{

 var MainPortServer = http.createServer( (req, res) =>{

     let dataString = "";
     req.on( "data", chunk => {
         let sChunk = chunk.toString( "utf8" );
         log( "MainPort Chunk: ", sChunk );
         dataString += sChunk;
     });

     req.on( "end", () => {
         let qParams = getAllRequestData( req , dataString );
         handlePortMainPortRequest( req, res, qParams );

     });

 });

 MainPortServer.on("error", err=>{
     console.error( err );
     log( ">>>>>>>>>>>>> TERMINATING")
     process.exit (1);
 });

 MainPortServer.listen( mainPort);
 log( "Web server [MainPort] listening on port " + mainPort )

} catch(e) {
console.error( e );
log( ">>>>>>>>>>>>> TERMINATING")
process.exit (1);
}

This is the function that processes the web request:

function handlePortMainPortRequest (req, res, qParams ) {

 if( !qParams.path || qParams.path.length == 0 ) { qParams.path = [ "reset" ] };

 switch( qParams.path[0] ){

     // This case handles a request for JSON structure of latest status
     case "pcl":

         // generate the JSON to be sent
         var pcl = plants.getPlantStatusList();

         // add the tick count and ticks per second stats
         pcl.push( { tick: forest.ticks(), tps: forest.tps() } );

         res.setHeader( "Content-type", "application/json" );
         res.end( JSON.stringify( pcl ) );
         return;

    //
    /// There are other cases here, not relevant to the question
    //

 }

}

Web page clips

This shows the normal tick rate without MSCode running (tick rate 76/ps):

And this is a snapshot taken while moving the mouse around on MSCode in the server through remote desktop (tick rate 517/s):


问:
How to change fragment's text from Service class?
I have a fragment that contains a TextView. Also, I have a class that extends Service.

How can I change fragment's TextView text from this Service class?
I tried to create an instance from my fragment to use it for calling an update method inside the fragment, but I realized that I can't call getSupportFragmentManager() inside a Service class.

So, what should I do?

答:
you can get getSupportFragmentManager() always and everywhere with below code using context:

```<code>((AppCompatActivity)context).getSupportFragmentManager();
</code>```

and to get fragment:

```<code>Fragment myFragment=((AppCompatActivity)context).getSupportFragmentManager().findFragmentById(R.id.your_fragment_id);
</code>```

after you access fragment you have two options to do your desired action.first is easier,second is more secure.

Option One->TextView Public
make textview public and setText() that textview from your service class like:

```<code>myFragment.myTextView.setText("some_text");
</code>```

Option Two->TextView Private
make textview private and create a method to setText() textview in fragment like:

```<code>public void setTextViewText(String text){
  textView.setText(text);
}
</code>```

and call it from your Service Class like:

```<code>myFragment.setTextViewText("some_text");
</code>```

Body:
you can get getSupportFragmentManager() always and everywhere with below code using context:

((AppCompatActivity)context).getSupportFragmentManager();

and to get fragment:

Fragment myFragment=((AppCompatActivity)context).getSupportFragmentManager().findFragmentById(R.id.your_fragment_id);

after you access fragment you have two options to do your desired action.first is easier,second is more secure.

Option One->TextView Public
make textview public and setText() that textview from your service class like:

myFragment.myTextView.setText("some_text");

Option Two->TextView Private
make textview private and create a method to setText() textview in fragment like:

public void setTextViewText(String text){
  textView.setText(text);
}

and call it from your Service Class like:

myFragment.setTextViewText("some_text");


问:
Position fixed doesn't work when using -webkit-transform
I am using -webkit-transform (and -moz-transform / -o-transform) to rotate a div. Also have position fixed added so the div scrolls down with the user.

In Firefox it works fine, but in webkit based browsers it's broken. After using the -webkit-transform, the position fixed doesn't work anymore! How is that possible?

答: in my case I found out we can't use transform: translateX() before transform:translateY().if we want to use both we should use transform:translate( , ).</p>


问:
ARGB to YUV && Color Spaces in .NET
I noticed that Color struct from System.Drawing represents color in ARGB color space. So there are some questions:

How to convert image beetween ARGB and YUV in c#? I found formulas describing RGB to YUV conversion. So what should I do with alpha channel?

Are there free/trial libraries that support different color spaces? Or how do I implement it myself in the best manner?

How do I represent 'Bitmap' as 2d array with ability to iterate over it? is Inheritance  the only way to accomplish this?

That's all yet)

Thanks!

答:
You cannot directly convert argb to YUV (without loss) cause YUV contains no alpha information.

Depending on what you wanna do with the color after you have these possibilities:

you just cut the alpha and discard the transparency

you convert to a AYUV which contains
also an alpha channel

conversion between color spaces

One possibility to convert a bitmap to a byte[] is to write it in a memorystream and read it bite wise.

```<code>MemoryStream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Bmp);
byte[] data = stream.ToArray();
</code>```

ContentLicense: CC BY-SA 3.0

Title: ARGB to YUV && Color Spaces in .NET

Body:
You cannot directly convert argb to YUV (without loss) cause YUV contains no alpha information.

Depending on what you wanna do with the color after you have these possibilities:

you just cut the alpha and discard the transparency

you convert to a AYUV which contains
also an alpha channel

conversion between color spaces

One possibility to convert a bitmap to a byte[] is to write it in a memorystream and read it bite wise.

MemoryStream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Bmp);
byte[] data = stream.ToArray();


问:
How to generate three unequal numbers?
Here the number generation :

```<code>for( int i=0; i<3; i++) {
    int randomNumbers = random.nextInt(10) + 1;
}
</code>```

And here I can receive the same digits.

For example: 5,7,5;

But I need to receive only different numbers: 5,1,9.

Is it possible maybe with some little piece of code or I should write some method for it?

答:
You can use a Set which holds only unique values:

```<code>Set<Integer> randomInts = new HashSet();
while(randomInts.size() < 3) {
    randomInts.add(random.nextInt(10) + 1);
}
</code>```

Of course, you need to face oversampling, but this approach scales very easily if performance isn't the most important.

Title: How to generate three unequal numbers?

Body:
Here the number generation :

for( int i=0; i<3; i++) {
    int randomNumbers = random.nextInt(10) + 1;
}

And here I can receive the same digits.

For example: 5,7,5;

But I need to receive only different numbers: 5,1,9.

Is it possible maybe with some little piece of code or I should write some method for it?

Body:
You can use a Set which holds only unique values:

Set<Integer> randomInts = new HashSet();
while(randomInts.size() < 3) {
    randomInts.add(random.nextInt(10) + 1);
}

Of course, you need to face oversampling, but this approach scales very easily if performance isn't the most important.


问:
value of using React.forwardRef vs custom ref prop
I see that React.forwardRef seems to be the sanctioned way of passing a ref to a child functional component, from the react docs:

```<code>const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
</code>```

However, what is the advantage of doing this over simply passing a custom prop?:

```<code>const FancyButton = ({ innerRef }) => (
  <button ref={innerRef} className="FancyButton">
    {props.children}
  </button>
));

const ref = React.createRef();
<FancyButton innerRef={ref}>Click me!</FancyButton>;
</code>```

The only advantage I can think of is maybe having a consistent api for refs, but is there any other advantage? Does passing a custom prop affect diffing when it comes to rendering and cause additional renders, surely not as the ref is stored as mutable state in the current field?

Say for example you wanted to pass multiple refs (which tbh, might indicate code smell, but still), then the only solution I can see would be to use customRef props.

I guess my question is what is the value of using forwardRef over a custom prop?

答:
Even React docs mention the custom ref prop as a more flexible approach to forwardRef:

If you use React 16.2 or lower, or if you need more flexibility than provided by ref forwarding, you can use this alternative approach and explicitly pass a ref as a differently named prop.

There is also a gist, in which Dan Abramov writes about its advantages:

compatible with all React versions

works for class and function components

simplifies passing a ref to a nested component several layers deep

I would add, that passing refs as usual props does not cause breaking changes and is the way to go for multiple refs. The only advantages of forwardRef coming to my mind are:

uniform access API for DOM nodes, functional and class components (you mentioned that)

ref attribute does not bloat your props API, e.g. if you provide types with TypeScript

Does passing a custom prop affect diffing when it comes to rendering and cause additional renders?

A ref can potentially trigger a re-render if you pass an inline callback ref function down as prop. But it is a better idea anyway to define it as class instance method or via some memoization like useCallback.

Body:
I see that React.forwardRef seems to be the sanctioned way of passing a ref to a child functional component, from the react docs:

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

However, what is the advantage of doing this over simply passing a custom prop?:

const FancyButton = ({ innerRef }) => (
  <button ref={innerRef} className="FancyButton">
    {props.children}
  </button>
));

const ref = React.createRef();
<FancyButton innerRef={ref}>Click me!</FancyButton>;

The only advantage I can think of is maybe having a consistent api for refs, but is there any other advantage? Does passing a custom prop affect diffing when it comes to rendering and cause additional renders, surely not as the ref is stored as mutable state in the current field?

Say for example you wanted to pass multiple refs (which tbh, might indicate code smell, but still), then the only solution I can see would be to use customRef props.

I guess my question is what is the value of using forwardRef over a custom prop?


问:
EE 5.x - How to suppress login/logout confirmation page
on EE 2.x the Freemember addon allowed to directly redirect the user after login/logout to a specified page (avoiding the default login/logout confirmation page).

Since the Freemember addon is EOL, how can I achieve the same thing on EE 5.x ?

答: I ended up using the member_member_login_single($hook_data) in a custom extension to get this done. Works.</p>


问:
How do I correctly define a function having numpy arrays as argument and return type?
As I see it, there are two options.(Here numpy is imported as np)

1. Using a lambda expression

This can be used when we are dealing with a simple function. Say I want to implement the function f:(x,y) = (x^2, x+y). Then I would expect some like this to work:

f = lambda x,y : x**2, x + y

f = lambda x,y : (x**2, x + y)

when i call print(f(np.array([[1],[3]],float))) or print(f(np.array([1,3],float))). But I cannot get any variant of these lambda expressions to work.

2. Defining a "proper" function

This however, does work:

```<code>def f(vec):
    return np.array([vec[0] ** 2, vec[0] + vec[1]])
</code>```

But is the syntax optimal? And how would I do it if i don't want the above "proper" function to be vectorized. In total, how do i define a numpy-array valued function taking numpy-array values?

答:
If you know that the input will always be an array of length 2, you can use:

```<code> f = lambda x : (x[0]**2, x[0] + x[1])
</code>```

Then, the examples you give also work.

Body:
As I see it, there are two options.(Here numpy is imported as np)

1. Using a lambda expression

This can be used when we are dealing with a simple function. Say I want to implement the function f:(x,y) = (x^2, x+y). Then I would expect some like this to work:

f = lambda x,y : x**2, x + y

f = lambda x,y : (x**2, x + y)

when i call print(f(np.array([[1],[3]],float))) or print(f(np.array([1,3],float))). But I cannot get any variant of these lambda expressions to work.

2. Defining a "proper" function

This however, does work:

def f(vec):
    return np.array([vec[0] ** 2, vec[0] + vec[1]])

But is the syntax optimal? And how would I do it if i don't want the above "proper" function to be vectorized. In total, how do i define a numpy-array valued function taking numpy-array values?

Body:
If you know that the input will always be an array of length 2, you can use:

 f = lambda x : (x[0]**2, x[0] + x[1])

Then, the examples you give also work.


问:
How to get support for thread_local on Mac OSX clang?
As shown in this answer, clang from Xcode on Mac OSX does not support thread_local storage even with C++11 flags set.  Even on the latest version, Apple LLVM version 7.0.0 (clang-700.1.76), Target: x86_64-apple-darwin15.0.0, Thread model: posix, does not support thread_local:

```<code>../../src/dir/sysArch.h:1505:3: error: thread-local storage is not supported
                                       for the current target
  thread_local
  ^
</code>```

答: You can use the old method of using pthread_getspecific() etc. to implement thread-local storage (or in Objective-C the NSThread's thread dictionary) if thread_local is not available in your compiler version.

Body:
As shown in this answer, clang from Xcode on Mac OSX does not support thread_local storage even with C++11 flags set.  Even on the latest version, Apple LLVM version 7.0.0 (clang-700.1.76), Target: x86_64-apple-darwin15.0.0, Thread model: posix, does not support thread_local:

../../src/dir/sysArch.h:1505:3: error: thread-local storage is not supported
                                       for the current target
  thread_local
  ^


问:
How are INI files used today?
I really like the "INI" file format:  Declarative KEY=VALUE, possibly embedded in named sections.

Further, I like the old "Make" style, where values set "higher" in the file may be interpolated into values "lower" in the file.  (I know that's not specifically INI style, but Makefiles behaved largely like INI files for values, which I liked, to centralize maintenance of values.)

This is still a popular file format for configurations, right?  If you were writing new tools today that relied upon configuration files, you'd use INI files, right?  How are INI files being used these days?

答:
If you were writing new tools today that relied upon configuration files, you'd
  use INI files, right?

No, I wouldn't. YAML (to choose one of many possible examples) is as concise as INI while giving your configs arbitrary depth (unlike INI, which gives you only two levels).

Title: How are INI files used today?


问:
Alt+Enter in Win32 apps, manage resizing and resolution
I'm struggling with resizing and full screen mode of my project. This is what I'm working on Mandelbrot in a Pixel Shader and here on GIT https://github.com/ShamanLKG/Mandelbrot

The app crashes when Alt+Enter is pressed and I don't understand why.

```<code>case WM_SIZE:
{
    int width = LOWORD(lParam);  // Macro to get the low-order word.
    int height = HIWORD(lParam); // Macro to get the high-order word.

    pThis->D3D->OnResize(width, height);
    pThis->D3D = std::shared_ptr<Direct3D>(new Direct3D(hWnd, width, height));
    pThis->D2D = std::shared_ptr<Direct2D>(new Direct2D(hWnd, pThis->D3D));
    break;
}
</code>```

I recreated the Direct3d and Direct2 objects on resize to solve issues with the navigation and to adjust the resolution of the window. But impossible so far to get the full screen working. The full screen works without recreating the D3D and D2D object but then I'm stucked with the original resolution and the navigation does not work properly. I use the OnResize() function from MSDN (https://learn.microsoft.com/en-us/windows/win32/direct3ddxgi/d3d10-graphics-programming-guide-dxgi#handling-window-resizing). I tried passing on a BOOL argument to InitD3D to tell the program if the swapchain is full screen or not from swapchain->GetFullScreenState but it did not help.

The navigation works as long at the window size is not changed, then it's not precise. Adjusting the yDelta with the change in screen ratio helps, but only when the window width is changed. It becomes again unstable when the window height is changed. So as workaround I recreated the D3D and D2D object to start with fresh parameters and having a function navigation. But as a result the full screen now crashes.

```<code>void Direct3D::CenterScreen(int xPos, int yPos)
{

    //float ratio = startRatio / currentRatio;
    int xDelta = xPos - width / 2;
    int yDelta = (yPos - height / 2);  //could divide by ratio to capture window width change

    realStart += (float)xDelta / (float)width * 2 * mandelWidth;
    imagStart += (float)yDelta / (float)height * 2 * mandelHeight;
}
</code>```

Any clue how I could solve these issues? Many thanks in advance.

答:
Found the error, the Direct2D resources were not released causing the ResizeBuffers to fail with code 0x887A0001. The tutorial from https://bell0bytes.eu/fullscreen/ has been very helpful.

```<code>hr = swapchain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0);
</code>```

Lesson of the day, have a robust error handling system.

Body:
I'm struggling with resizing and full screen mode of my project. This is what I'm working on Mandelbrot in a Pixel Shader and here on GIT https://github.com/ShamanLKG/Mandelbrot

The app crashes when Alt+Enter is pressed and I don't understand why.

case WM_SIZE:
{
    int width = LOWORD(lParam);  // Macro to get the low-order word.
    int height = HIWORD(lParam); // Macro to get the high-order word.

    pThis->D3D->OnResize(width, height);
    pThis->D3D = std::shared_ptr<Direct3D>(new Direct3D(hWnd, width, height));
    pThis->D2D = std::shared_ptr<Direct2D>(new Direct2D(hWnd, pThis->D3D));
    break;
}

I recreated the Direct3d and Direct2 objects on resize to solve issues with the navigation and to adjust the resolution of the window. But impossible so far to get the full screen working. The full screen works without recreating the D3D and D2D object but then I'm stucked with the original resolution and the navigation does not work properly. I use the OnResize() function from MSDN (https://learn.microsoft.com/en-us/windows/win32/direct3ddxgi/d3d10-graphics-programming-guide-dxgi#handling-window-resizing). I tried passing on a BOOL argument to InitD3D to tell the program if the swapchain is full screen or not from swapchain->GetFullScreenState but it did not help.

The navigation works as long at the window size is not changed, then it's not precise. Adjusting the yDelta with the change in screen ratio helps, but only when the window width is changed. It becomes again unstable when the window height is changed. So as workaround I recreated the D3D and D2D object to start with fresh parameters and having a function navigation. But as a result the full screen now crashes.

void Direct3D::CenterScreen(int xPos, int yPos)
{

    //float ratio = startRatio / currentRatio;
    int xDelta = xPos - width / 2;
    int yDelta = (yPos - height / 2);  //could divide by ratio to capture window width change

    realStart += (float)xDelta / (float)width * 2 * mandelWidth;
    imagStart += (float)yDelta / (float)height * 2 * mandelHeight;
}

Any clue how I could solve these issues? Many thanks in advance.

Body:
Found the error, the Direct2D resources were not released causing the ResizeBuffers to fail with code 0x887A0001. The tutorial from https://bell0bytes.eu/fullscreen/ has been very helpful.

hr = swapchain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0);

Lesson of the day, have a robust error handling system.


问:
Docker-compose volume doesn't save state of container for Keycloak
docker-compose.yml

```<code>services:
  idprovider-app:
    container_name: idprovider-app
    build:
      dockerfile: Dockerfile
      context: .
    environment:
      KEYCLOAK_USER: admin
      KEYCLOAK_PASSWORD: admin
    volumes:
        - keycloak-data-volume:/var/lib/keycloak/data
    ports:
      - "8090:8090"
      - "8443:8443"
volumes:
  keycloak-data-volume:
    external: true
</code>```

dockerfile

```<code>FROM jboss/keycloak:7.0.1
EXPOSE 8080
EXPOSE 8443
</code>```

docker inspect "container"

```<code>"Mounts": [
            {
                "Type": "volume",
                "Name": "keycloak-data-volume",
                "Source": "/mnt/sda1/var/lib/docker/volumes/keycloak-data-volume/_data",
                "Destination": "/var/lib/keycloak/data",
                "Driver": "local",
                "Mode": "rw",
                "RW": true,
                "Propagation": ""
            }
        ],
</code>```

docker volume inspect keycloak-data-volume

```<code>[
    {
        "CreatedAt": "2019-12-10T19:31:55Z",
        "Driver": "local",
        "Labels": {},
        "Mountpoint": "/mnt/sda1/var/lib/docker/volumes/keycloak-data-volume/_data",
        "Name": "keycloak-data-volume",
        "Options": {},
        "Scope": "local"
    }
]
</code>```

There isn't errors, but it doesn't save state. I have no any idea what's wrong. I run it on Windows 10.

答:
You must specify the source of the database in the environment variables.
If you used a different service for the PostgreSQL instance for postgres, you must specify the DB_ADDR environment variable in your service.</p>

```<code>services:
  idprovider-app:
    container_name: idprovider-app
    build:
      dockerfile: Dockerfile
      context: .
    environment:
      DB_VENDOR: POSTGRES
      # Specify hostname of the database (eg: hostname or hostname:port)
      DB_ADDR: hostname:5432
      DB_DATABASE: keycloak
      DB_USER: keycloak
      DB_SCHEMA: public
      DB_PASSWORD: password
      KEYCLOAK_USER: admin
      KEYCLOAK_PASSWORD: admin
    volumes:
        - keycloak-data-volume:/var/lib/keycloak/data
    ports:
      - "8090:8090"
      - "8443:8443"
volumes:
  keycloak-data-volume:
    external: true
</code>```

Body:
docker-compose.yml

services:
  idprovider-app:
    container_name: idprovider-app
    build:
      dockerfile: Dockerfile
      context: .
    environment:
      KEYCLOAK_USER: admin
      KEYCLOAK_PASSWORD: admin
    volumes:
        - keycloak-data-volume:/var/lib/keycloak/data
    ports:
      - "8090:8090"
      - "8443:8443"
volumes:
  keycloak-data-volume:
    external: true

dockerfile

FROM jboss/keycloak:7.0.1
EXPOSE 8080
EXPOSE 8443

docker inspect "container"

"Mounts": [
            {
                "Type": "volume",
                "Name": "keycloak-data-volume",
                "Source": "/mnt/sda1/var/lib/docker/volumes/keycloak-data-volume/_data",
                "Destination": "/var/lib/keycloak/data",
                "Driver": "local",
                "Mode": "rw",
                "RW": true,
                "Propagation": ""
            }
        ],

docker volume inspect keycloak-data-volume

[
    {
        "CreatedAt": "2019-12-10T19:31:55Z",
        "Driver": "local",
        "Labels": {},
        "Mountpoint": "/mnt/sda1/var/lib/docker/volumes/keycloak-data-volume/_data",
        "Name": "keycloak-data-volume",
        "Options": {},
        "Scope": "local"
    }
]

There isn't errors, but it doesn't save state. I have no any idea what's wrong. I run it on Windows 10.

Body:
You must specify the source of the database in the environment variables.
If you used a different service for the PostgreSQL instance for postgres, you must specify the DB_ADDR environment variable in your service.

services:
  idprovider-app:
    container_name: idprovider-app
    build:
      dockerfile: Dockerfile
      context: .
    environment:
      DB_VENDOR: POSTGRES
      # Specify hostname of the database (eg: hostname or hostname:port)
      DB_ADDR: hostname:5432
      DB_DATABASE: keycloak
      DB_USER: keycloak
      DB_SCHEMA: public
      DB_PASSWORD: password
      KEYCLOAK_USER: admin
      KEYCLOAK_PASSWORD: admin
    volumes:
        - keycloak-data-volume:/var/lib/keycloak/data
    ports:
      - "8090:8090"
      - "8443:8443"
volumes:
  keycloak-data-volume:
    external: true


问:
ReactJS: onClick function executes before clicking button
The function SendCred() executes the page is loading, but I want this to be called when the user clicks the <button>. What should I do?

```<code> import React,{useState} from "react";

    export default function Signup(props){

      const sendCred=()=>{
        console.log("test")
      };

      return (
        <div className="row container">
          <button onClick={sendCred()}> Activate Laser </button>
        </div>
      );

    };
</code>```

答:
You are executing the function sendCred by calling it inside the onClick using "sendCred()". That event listener receives a function so you should assign sendCred alone.

Like this:

```<code> return (
   <div className="row container">
     <button onClick={sendCred}>Activate Laser</button>
   </div>
 );
</code>```

For the function you should know that you will receive the event that may be useful for you.

```<code> const sendCred = useCallback((event) => {
   console.log('This is the click event:', event);
   console.log("test");
 });
</code>```

As the onClick receives a function you can use clousures to take advantage of having some value you want sent along with the event.

The code will look something like this:

```<code>   import React, {useState} from "react";

   export default function Signup(props) {

     const sendCred = useCallback((value) => (event) => {
       console.log("I have a value:", value);
       console.log("I have an event:", event);
     });

     return (
       <div className="row container">
         <button onClick={sendCred('Laser')}>Activate Laser</button>
         <button onClick={sendCred('Engine')}>Activate Engine</button>
       </div>
     );
   };
</code>```

That works because you return a function with value available for it to use and when the button is clicked the second function is executed with the event as a parameter.

hope it helps! ;)

Body:
The function SendCred() executes the page is loading, but I want this to be called when the user clicks the <button>. What should I do?

 import React,{useState} from "react";

    export default function Signup(props){

      const sendCred=()=>{
        console.log("test")
      };

      return (

          <button onClick={sendCred()}> Activate Laser </button>

      );

    };

Body:
You are executing the function sendCred by calling it inside the onClick using "sendCred()". That event listener receives a function so you should assign sendCred alone.

Like this:

 return (
   <div className="row container">
     <button onClick={sendCred}>Activate Laser</button>
   </div>
 );

For the function you should know that you will receive the event that may be useful for you.

 const sendCred = useCallback((event) => {
   console.log('This is the click event:', event);
   console.log("test");
 });

As the onClick receives a function you can use clousures to take advantage of having some value you want sent along with the event.

The code will look something like this:

   import React, {useState} from "react";

   export default function Signup(props) {

     const sendCred = useCallback((value) => (event) => {
       console.log("I have a value:", value);
       console.log("I have an event:", event);
     });

     return (
       <div className="row container">
         <button onClick={sendCred('Laser')}>Activate Laser</button>
         <button onClick={sendCred('Engine')}>Activate Engine</button>
       </div>
     );
   };

That works because you return a function with value available for it to use and when the button is clicked the second function is executed with the event as a parameter.

hope it helps! ;)


问:
How to Integrate Rails User Authentication and Authorization with a Front End App?
Can anyone point out a good resource on how to implement authentication/authorization using Rails API with React?

I've been spending a week or two trying to figure out how to combine the two and I haven't been able to, it's driving me insane.

There are people who says HTTP cookie only authentication is better whereas some people say token authentications are better. Then comes authorization. Then connecting. There's so much going on at once I can't decipher what method is the best practice.

Right now I am trying to use devise and pundit for authenticating and authorizing users, but then there are gems like simple-token-authentication, Knock, etc..

Please help me out.

Thank you.

答:
for rails server part you can use bcrypt / devise to authenticate user if it's correct  and then using JsonWebToken to generate token and returned it to user and here is sample to encode using JsonWebToken

Gemfile

```<code>gem 'devise'
gem 'jwt', '~> 2.2'
</code>```

controller/api/tokens_Controller.rb

```<code>class TokensController < ApplicationController
  def create
    @user = User.find_by_email(user_params[:email])
    if @user && @user.valid_password?(user_params[:password])
      render json: {
        token: JsonWebToken.encode(user_id: @user.id),
        email: @user.email
      }
    else
      head :unauthorized
    end
  end

  private

  def user_params
    params.require(:user).permit(:email, :password)
  end
end
</code>```

and here is good book to read if you want to learn more, API on rails 6 by Alexandre,

on React part you can use Axios and if user success authenticated then received token, you can set token to be valid as long as you like (1 day, 1 week, 2 months etc), each time user request page / data that need authentication, user must send the token (you can put inside http header) here is sample from react part

```<code>import axios from 'axios';

export default axios.create({
  baseURL: 'http://your_api_server/api',
  headers: {
    Authorization: {put your token here}
  }
})
</code>```

Body:
for rails server part you can use bcrypt / devise to authenticate user if it's correct  and then using JsonWebToken to generate token and returned it to user and here is sample to encode using JsonWebToken

Gemfile

gem 'devise'
gem 'jwt', '~> 2.2'

controller/api/tokens_Controller.rb

class TokensController < ApplicationController
  def create
    @user = User.find_by_email(user_params[:email])
    if @user && @user.valid_password?(user_params[:password])
      render json: {
        token: JsonWebToken.encode(user_id: @user.id),
        email: @user.email
      }
    else
      head :unauthorized
    end
  end

  private

  def user_params
    params.require(:user).permit(:email, :password)
  end
end

and here is good book to read if you want to learn more, API on rails 6 by Alexandre,

on React part you can use Axios and if user success authenticated then received token, you can set token to be valid as long as you like (1 day, 1 week, 2 months etc), each time user request page / data that need authentication, user must send the token (you can put inside http header) here is sample from react part

import axios from 'axios';

export default axios.create({
  baseURL: 'http://your_api_server/api',
  headers: {
    Authorization: {put your token here}
  }
})


问:
How to get current offset of stream or file descriptor?
In Node.js, is there any way of getting the current offset of a file descriptor or stream? Presently, it is possible to set the offset of a file descriptor, but there seems to be no way to get it.

In C, getting the offset of a file stream is done via ftell, and a file descriptor via lseek(fd, 0, SEEK_CUR).

Example

If a Node.js program needs to check whether there is prior data in a file after opening it in append mode, a call to ftell would help in this case. This can be done in C as follows:

#include <stdio.h>

int main() {
    FILE* f = fopen("test.txt", "a");
    fprintf(f, ftell(f) ? "Subsequent line\n" : "First line\n");
    fclose(f);
}
```

<p>Running the above program three times, <code>test.txt</code> becomes:</p>

```First line
Subsequent line
Subsequent line
```

Prior Art

GitHub issue filed for old version of node. The discussion mentions bytesWritten and bytesEmitted, neither of which is equivalent to ftell (in the above C example, the bytes written when the file is first opened is always 0). https://github.com/nodejs/node-v0.x-archive/issues/1527.

The fs-ext NPM package. Exposes the low-level lseek for use in Node.js. https://www.npmjs.com/package/fs-ext.

答:
There is no equivalent to ftell() or fseek() in node.js and I'm not really sure why.  Instead, you generally specify the position you want to read or write at whenever you read or write with fs.read() or fs.write().  If you want to just write a bunch of data sequentially or you want buffered writing, then you would more typically use a stream which buffers and sequences for you.

Instead, if you want to know where data will be appended, you can fetch the current file length and then use that current file length to know if you're at the beginning of the file after opening it for appending.

Here's node.js code that does something similar to your C code.

```<code>const fs = require('fs');

async function myFunc() {
     let handle = await fs.promises.open("test.txt");
     try {
         const {size} = await handle.stat();
         await handle.appendFile(size ? "Subsequent line\n" : "First line\n");
     } finally {
         await handle.close();
     }
}
</code>```

And, if you call this three times like this:

```<code>async function test() {
    await myFunc();
    await myFunc();
    await myFunc();
}

test();
</code>```

You will get your desired three lines in the file:

```<code>First line
Subsequent line
Subsequent line
</code>```

Body:
In Node.js, is there any way of getting the current offset of a file descriptor or stream? Presently, it is possible to set the offset of a file descriptor, but there seems to be no way to get it.

In C, getting the offset of a file stream is done via ftell, and a file descriptor via lseek(fd, 0, SEEK_CUR).

Example

If a Node.js program needs to check whether there is prior data in a file after opening it in append mode, a call to ftell would help in this case. This can be done in C as follows:

#include <stdio.h>

int main() {
    FILE* f = fopen("test.txt", "a");
    fprintf(f, ftell(f) ? "Subsequent line\n" : "First line\n");
    fclose(f);
}

Running the above program three times, test.txt becomes:

First line
Subsequent line
Subsequent line

Prior Art

GitHub issue filed for old version of node. The discussion mentions bytesWritten and bytesEmitted, neither of which is equivalent to ftell (in the above C example, the bytes written when the file is first opened is always 0). https://github.com/nodejs/node-v0.x-archive/issues/1527.

The fs-ext NPM package. Exposes the low-level lseek for use in Node.js. https://www.npmjs.com/package/fs-ext.

Body:
There is no equivalent to ftell() or fseek() in node.js and I'm not really sure why.  Instead, you generally specify the position you want to read or write at whenever you read or write with fs.read() or fs.write().  If you want to just write a bunch of data sequentially or you want buffered writing, then you would more typically use a stream which buffers and sequences for you.

Instead, if you want to know where data will be appended, you can fetch the current file length and then use that current file length to know if you're at the beginning of the file after opening it for appending.

Here's node.js code that does something similar to your C code.

const fs = require('fs');

async function myFunc() {
     let handle = await fs.promises.open("test.txt");
     try {
         const {size} = await handle.stat();
         await handle.appendFile(size ? "Subsequent line\n" : "First line\n");
     } finally {
         await handle.close();
     }
}

And, if you call this three times like this:

async function test() {
    await myFunc();
    await myFunc();
    await myFunc();
}

test();

You will get your desired three lines in the file:

First line
Subsequent line
Subsequent line


问:
Is it possible to replace each capturing group in a regex with a different string
If I have a regex like this: (\.\d+)|([A-Z]\d{2}\.-)

Can I replace capturing group $1 with string a and capturing group $2 with string b within one regex replace?

```<code>preg_replace($pattern, $replace, $value);
</code>```

.123A12.- to Value-aValue-b or .123funA12 to Value-afunValue-b

答:
This is how I solved it:

```<code><?php
$patterns = array ('/\.\d+/','/[A-Z]\d{2}\.-/');
$replace = array ('Value-a','Value-b');
echo preg_replace($patterns, $replace, '.123funA12.-');
?>
</code>```

See here and here for information.

Body:
If I have a regex like this: (\.\d+)|([A-Z]\d{2}\.-)

Can I replace capturing group $1 with string a and capturing group $2 with string b within one regex replace?

preg_replace($pattern, $replace, $value);

.123A12.- to Value-aValue-b or .123funA12 to Value-afunValue-b

Body:
This is how I solved it:

<?php
$patterns = array ('/\.\d+/','/[A-Z]\d{2}\.-/');
$replace = array ('Value-a','Value-b');
echo preg_replace($patterns, $replace, '.123funA12.-');
?>

See here and here for information.


问:
Do I have to cast an Object object to a specific type before using it in my contains and equals method?
So I have a Hospital class and inside it, I have a method called remove(Object object) which checks what kind of Object the parameter input is. Then after finding the instance of the object I use my equals method to find the object in the ArrayList to remove. My question is, do I have to cast the object to the specific type before using it?
Something like this: .........equals((Patient) object))?</p>

```<code>public boolean remove(Object object) {
        if(object instanceof Department){
            departments.remove(object);
            return true;
        }
        if(object instanceof Patient){
            for(int i = 0; i < departments.size(); i ++){
                for(int j = 0; j < departments.size(); j ++) {
                    if (departments.get(i).getPatients().get(j).equals(object)) {
                        departments.get(i).getPatients().remove(j);
                        return true;
                    }
                }
            }
        }
        if(object instanceof Employee){
            for(int i = 0; i < departments.size(); i ++){
                for(int j = 0; j < departments.size(); j ++) {
                    if (departments.get(i).getEmployees().get(j).equals(object)) {
                        departments.get(i).getEmployees().remove(j);
                        return true;
                    }
                }
            }
        }
        return false;
    }
</code>```

答:
Dorian Gray's answer is fine, but a recommendation for refactoring:

implement equals and hashCode on your classes

make departments a collection, if it is not already

use Java's for-each loop (or streams)

So the double for-loops become

```<code>...
for (Department department : departments) {
  if (department.getEmployees().contains(object)) {
    department.getEmployees().remove(object);
    return true;
  }
}
...
</code>```

Body:
So I have a Hospital class and inside it, I have a method called remove(Object object) which checks what kind of Object the parameter input is. Then after finding the instance of the object I use my equals method to find the object in the ArrayList to remove. My question is, do I have to cast the object to the specific type before using it?
Something like this: .........equals((Patient) object))?

public boolean remove(Object object) {
        if(object instanceof Department){
            departments.remove(object);
            return true;
        }
        if(object instanceof Patient){
            for(int i = 0; i < departments.size(); i ++){
                for(int j = 0; j < departments.size(); j ++) {
                    if (departments.get(i).getPatients().get(j).equals(object)) {
                        departments.get(i).getPatients().remove(j);
                        return true;
                    }
                }
            }
        }
        if(object instanceof Employee){
            for(int i = 0; i < departments.size(); i ++){
                for(int j = 0; j < departments.size(); j ++) {
                    if (departments.get(i).getEmployees().get(j).equals(object)) {
                        departments.get(i).getEmployees().remove(j);
                        return true;
                    }
                }
            }
        }
        return false;
    }

Body:
Dorian Gray's answer is fine, but a recommendation for refactoring:

implement equals and hashCode on your classes

make departments a collection, if it is not already

use Java's for-each loop (or streams)

So the double for-loops become

...
for (Department department : departments) {
  if (department.getEmployees().contains(object)) {
    department.getEmployees().remove(object);
    return true;
  }
}
...


问:
Writing computed data to a txt/csv after each iterations step
Consider the following simple example:

```<code>x1, x2, x3, x4 = 0, 0, 0, 0
index = 0

for i in range(3):
    index += 1
    x1 += 2
    x2 += 2
    x3 += 2
    x4 += 2
</code>```

How can i create a txt or csv file that stores x1,x2,x3,x4 and index after each iteration in separate columns (5 in total). Is it also possible to give each column a title?

The end result should look like

```<code>Index    Data1    Data2    Data3    Data4
1        2        2        2        2
2        4        4        4        4
3        6        6        6        6
</code>```

It is important that the stored data is well separated because it will be later used for another computation. If the variable with the stored values is called " data_ " , i want to apply slice operations, e.g. data_[:,0] = [1,2,3].

Edit:
@abc i tried your method but it does not work

```<code>import pandas as pd
from numpy import array

index = 0

for i in range(3):
    index += 1
    x1 += 2
    x2 += 2
    x3 += 2
    compact = [[index, x1, x2, x3]]
    pd.DataFrame(compact, columns=   ['Index','Data1','Data2','Data3']).to_csv('example.csv',index=False)
</code>```

The example.csv file will only obtain the last computed values, e.g.

In my real program it is not possible to first store all the computed values (10^6 iterations) and only afterwards to save them. The values need to be stored after each iteration!

答:
You can use pandas for this. This assumes having all the data. Example.

```<code>res = [[1,2,2,2,2],[2,4,4,4,4]]
pd.DataFrame(res, columns=['Index','Data1','Data2','Data3','Data4']).to_csv('example.csv',index=False)
</code>```

In case you want to store the new row after each iteration what you can do is:

```<code>with open('res.csv','w') as f:
   f.write('Index,Data1,Data2,Data3\n')
   # for each iteration
        # compute new row
        f.write(",".join(map(str,row)))
        f.write("\n")
</code>```

Body:
Consider the following simple example:

x1, x2, x3, x4 = 0, 0, 0, 0
index = 0

for i in range(3):
    index += 1
    x1 += 2
    x2 += 2
    x3 += 2
    x4 += 2

How can i create a txt or csv file that stores x1,x2,x3,x4 and index after each iteration in separate columns (5 in total). Is it also possible to give each column a title?

The end result should look like

Index    Data1    Data2    Data3    Data4
1        2        2        2        2
2        4        4        4        4
3        6        6        6        6

It is important that the stored data is well separated because it will be later used for another computation. If the variable with the stored values is called " data_ " , i want to apply slice operations, e.g. data_[:,0] = [1,2,3].

Edit:
@abc i tried your method but it does not work

import pandas as pd
from numpy import array

index = 0

for i in range(3):
    index += 1
    x1 += 2
    x2 += 2
    x3 += 2
    compact = [[index, x1, x2, x3]]
    pd.DataFrame(compact, columns=   ['Index','Data1','Data2','Data3']).to_csv('example.csv',index=False)

The example.csv file will only obtain the last computed values, e.g.

In my real program it is not possible to first store all the computed values (10^6 iterations) and only afterwards to save them. The values need to be stored after each iteration!

Body:
You can use pandas for this. This assumes having all the data. Example.

res = [[1,2,2,2,2],[2,4,4,4,4]]
pd.DataFrame(res, columns=['Index','Data1','Data2','Data3','Data4']).to_csv('example.csv',index=False)

In case you want to store the new row after each iteration what you can do is:

with open('res.csv','w') as f:
   f.write('Index,Data1,Data2,Data3\n')
   # for each iteration
        # compute new row
        f.write(",".join(map(str,row)))
        f.write("\n")


问:
PostgreSQL:update column with dates and return values
I have a table:

For example current date 04/02/2020

```<code>  id   |   last_update   | update_frequency(days)
--------------------------------------------------
   1    |   01/02/2020   |   2
   2    |   01/02/2020   |   1
   3    |   01/02/2020   |   5
</code>```

I would like to make a single query that will return ids to update.

```<code>   id   |
---------
    1
    2
</code>```

答:
You can use the following:</p>

```<code>select id
from table_name
where extract('day' from (last_update - current_date)) >= update_frequency
</code>```

Body:
I have a table:

For example current date 04/02/2020

  id   |   last_update   | update_frequency(days)
--------------------------------------------------
   1    |   01/02/2020   |   2
   2    |   01/02/2020   |   1
   3    |   01/02/2020   |   5

I would like to make a single query that will return ids to update.

   id   |
---------
    1
    2

Body:
You can use the following:

select id
from table_name
where extract('day' from (last_update - current_date)) >= update_frequency


问:
How to resolve Ninja c++ build and execution
I have a C++ project based on CMake that uses Ninja. It's been build and ran using eclipse for C/C++. My current machine is a Mac OS.
The file:

```<code>#include <iostream>
#include <exception>
#include <string>
#include <stdexcept>
#include <vector>
#include <cmath>
using namespace std;

class Server {
private:
    static int load;
public:
    static int compute(long long A, long long B) {
        load += 1;
        if(A < 0) {
            throw std::invalid_argument("A is negative");
        }
        vector<int> v(A, 0);
        int real = -1, cmplx = sqrt(-1);
        if(B == 0) throw 0;
        real = (A/B)*real;
        int ans = v.at(B);
        return real + A - B*ans;
    }
    static int getLoad() {
        return load;
    }
};
int Server::load = 0;

int main() {
    int T;
    cin >> T;
    while(T--) {
        long long A, B;
        cin >> A >> B;

        /* Enter your code here. */
                try{
            cout << Server::compute(A, B) << endl;
        } catch(invalid_argument e){
            cout << "Exception: A is negative" << endl;
        } catch(bad_alloc &e){
            cout << "Not enough memory" << endl;
        } catch(exception &e){
            cout << "Exception: ";
            cout << e.what() << endl;
        } catch(...){
            cout << "Other Exception" << endl;
        }
    }
    cout << Server::getLoad() << endl;
    return 0;
}
</code>```

Build info:

```<code>cmake --build . -- -v
[1/2] /Library/Developer/CommandLineTools/usr/bin/c++    -O3 -DNDEBUG -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk -MD -MT CMakeFiles/deleteme.dir/deleteme.cpp.o -MF CMakeFiles/deleteme.dir/deleteme.cpp.o.d -o CMakeFiles/deleteme.dir/deleteme.cpp.o -c ../../deleteme.cpp
[2/2] : && /Library/Developer/CommandLineTools/usr/bin/c++  -O3 -DNDEBUG -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names  CMakeFiles/deleteme.dir/deleteme.cpp.o  -o deleteme   && :
Build complete (0 errors, 0 warnings):
</code>```

When I run:

```<code>Building in:
cmake --build . -- -v
ninja: no work to do.
Build complete (0 errors, 0 warnings):
</code>```

It does not give me the chance to input the values. It just skips everything and finishes execution. If I put a cout right at the beginning, then the program works as expected.

Why is this happening?

Ps: The project complete path was removed from here for safety reasons. And yes, my project was created with the name 'deleteme'.

Pss: I took this snippet from HackerRank for studing purposes, so It should be fine. I've only added the try/catch and method call.

答:
You are confusing building your program with running your program.

When you run the command cmake --build . -- -v, cmake will build your project. That means it will launch the appropriate tools to compile and link your program, which will produce an executable called deleteme somewhere in your build directory.
The subsequent invocation of the same command correctly reports that no work needs to be done (since you presumably haven't modified any of the source code between invocations).
To be clear, normally this will not run your program, which is why you don't get a prompt to input any values.

To run your program, which, if I understand correctly is what you are trying to do, simply run the executable deleteme that was produced by the build process. You will most likely find this executable in the build directory, that is, the directory where you ran the cmake --build . command. (Depending on your CMake project structure, you may also find it in a subdirectory of your build directory.)

Body:
I have a C++ project based on CMake that uses Ninja. It's been build and ran using eclipse for C/C++. My current machine is a Mac OS.
The file:

#include <iostream>
#include <exception>
#include <string>
#include <stdexcept>
#include <vector>
#include <cmath>
using namespace std;

class Server {
private:
    static int load;
public:
    static int compute(long long A, long long B) {
        load += 1;
        if(A < 0) {
            throw std::invalid_argument("A is negative");
        }
        vector<int> v(A, 0);
        int real = -1, cmplx = sqrt(-1);
        if(B == 0) throw 0;
        real = (A/B)*real;
        int ans = v.at(B);
        return real + A - B*ans;
    }
    static int getLoad() {
        return load;
    }
};
int Server::load = 0;

int main() {
    int T;
    cin >> T;
    while(T--) {
        long long A, B;
        cin >> A >> B;

        /* Enter your code here. */
                try{
            cout << Server::compute(A, B) << endl;
        } catch(invalid_argument e){
            cout << "Exception: A is negative" << endl;
        } catch(bad_alloc &e){
            cout << "Not enough memory" << endl;
        } catch(exception &e){
            cout << "Exception: ";
            cout << e.what() << endl;
        } catch(...){
            cout << "Other Exception" << endl;
        }
    }
    cout << Server::getLoad() << endl;
    return 0;
}

Build info:

cmake --build . -- -v
[1/2] /Library/Developer/CommandLineTools/usr/bin/c++    -O3 -DNDEBUG -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk -MD -MT CMakeFiles/deleteme.dir/deleteme.cpp.o -MF CMakeFiles/deleteme.dir/deleteme.cpp.o.d -o CMakeFiles/deleteme.dir/deleteme.cpp.o -c ../../deleteme.cpp
[2/2] : && /Library/Developer/CommandLineTools/usr/bin/c++  -O3 -DNDEBUG -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names  CMakeFiles/deleteme.dir/deleteme.cpp.o  -o deleteme   && :
Build complete (0 errors, 0 warnings):

When I run:

Building in:
cmake --build . -- -v
ninja: no work to do.
Build complete (0 errors, 0 warnings):

It does not give me the chance to input the values. It just skips everything and finishes execution. If I put a cout right at the beginning, then the program works as expected.

Why is this happening?

Ps: The project complete path was removed from here for safety reasons. And yes, my project was created with the name 'deleteme'.

Pss: I took this snippet from HackerRank for studing purposes, so It should be fine. I've only added the try/catch and method call.