问:
How to center an image on React
Apologies because this is kind of a simple question, but I have tried a lot of things but still cannot find the solution to center this image: className="meme--image"
I just want that image to be in the center of the page.

Here is my CSS code:

```<code>.form {
    gap: 20px;
    padding-top: 40px;
    padding-left: 50px;
    padding-right: 40px;
    border-radius: 5px;
    display: grid;
    grid-template: 40px 40px  / 1fr 1fr;
}

.form--submit {
    grid-column: 1/ -1;
    background: linear-gradient(90deg, #672280 1.18%, #A626D3 100%);
    color: white;
    border: none;
    cursor: pointer;
    font-family: "Karla", sans-serif;
    border-radius: 5px;
}

.form--input {
    border: 1px solid #D5D4D8;
    border-radius: 0.3125rem;
    font-family: inherit;
    text-indent: 5px;
}
</code>```

Here is my HTML code:

```<code>export default function Input() {
    return (
        <div>
            <div className="form">
                <input type="text" className="form--input" placeholder="Top text" />
                <input type="text" className="form--input" placeholder="Bottom text" />
                <button className="form--submit" onClick={getMemeImage}> Get a new meme image </button>
            </div>
            <img src="https://i.imgflip.com/3lmzyx.jpg"className="meme--image" />
        </div>
    )
}
</code>```

答:
just give image some height width and make margin auto.</p>
```<code>
.meme--image{
   width:400px;
   margin: 0 auto;
}

</code>```

Title: How to center an image on React

Body:
Apologies because this is kind of a simple question, but I have tried a lot of things but still cannot find the solution to center this image: className="meme--image"
I just want that image to be in the center of the page.

Here is my CSS code:

.form {
    gap: 20px;
    padding-top: 40px;
    padding-left: 50px;
    padding-right: 40px;
    border-radius: 5px;
    display: grid;
    grid-template: 40px 40px  / 1fr 1fr;
}

.form--submit {
    grid-column: 1/ -1;
    background: linear-gradient(90deg, #672280 1.18%, #A626D3 100%);
    color: white;
    border: none;
    cursor: pointer;
    font-family: "Karla", sans-serif;
    border-radius: 5px;
}

.form--input {
    border: 1px solid #D5D4D8;
    border-radius: 0.3125rem;
    font-family: inherit;
    text-indent: 5px;
}

Here is my HTML code:

export default function Input() {
    return (

                <input type="text" className="form--input" placeholder="Top text" />
                <input type="text" className="form--input" placeholder="Bottom text" />
                <button className="form--submit" onClick={getMemeImage}> Get a new meme image </button>

    )
}

Body:
just give image some height width and make margin auto.

.meme--image{
   width:400px;
   margin: 0 auto;
}


来源: stackexchange

问:
In Android Studio, I am not able to move google map and it always returns to current location

My problem is: When I'm trying to move around in the map or zoom in & out it immediately return to my current location. Also when I search for location, new marker added at the searched location but immediately goes back to my current location.
I searched for solution but found nothing.. I hope somebody can figure it out

```<code>    package com.hitman.locationrevision;
    import androidx.annotation.NonNull;
    import androidx.core.app.ActivityCompat;
    import androidx.core.content.ContextCompat;
    import androidx.fragment.app.FragmentActivity;

    import android.Manifest;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.location.LocationRequest;
    import android.os.Bundle;
    import android.widget.Toast;

    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.MarkerOptions;
    import com.hitman.locationrevision.databinding.ActivityMapsBinding;

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
        LocationManager locationManager;
        LocationListener locationListener;

    >function for current location information
        public void locationInfo(Location location,String title){
            if(location != null) {
                LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(currentLocation).title(title));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation,10));
            }
        }
    >function to request permission from user
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
                    Location lastLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    locationInfo(lastLocation,"Your lastLocation");
                }

            }
        }

        private GoogleMap mMap;
        private ActivityMapsBinding binding;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            binding = ActivityMapsBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());

            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            Intent intent=getIntent();
            locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            locationListener=new LocationListener() {
                @Override
                public void onLocationChanged(@NonNull Location location) {
                    locationInfo(location,"Your Location");
                }
            };
>code to ask permission and check permission from user

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
            }else{

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
>code to find the last location and update the last location
                Location
        lastLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    locationInfo(lastLocation,"Your lastlocation");
            }

        }
    }
</code>```

答:
Its because you have move camera when your location update. You just need to put condition whether its user call or not to see current location.

Here is the line, this will alway move camera and display your current location

```<code>mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation,10));
</code>```

You can do like this, whenever user required to see current location then change fromUser = true and then make to false back. Just like happen in Google Map when you click on location button.

```<code>var fromUser = false;

if(fromUser){
     mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation,10));
     fromUser = false;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My problem is: When I'm trying to move around in the map or zoom in & out it immediately return to my current location. Also when I search for location, new marker added at the searched location but immediately goes back to my current location.
I searched for solution but found nothing.. I hope somebody can figure it out

    package com.hitman.locationrevision;
    import androidx.annotation.NonNull;
    import androidx.core.app.ActivityCompat;
    import androidx.core.content.ContextCompat;
    import androidx.fragment.app.FragmentActivity;

    import android.Manifest;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.location.LocationRequest;
    import android.os.Bundle;
    import android.widget.Toast;

    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.MarkerOptions;
    import com.hitman.locationrevision.databinding.ActivityMapsBinding;

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
        LocationManager locationManager;
        LocationListener locationListener;

    >function for current location information
        public void locationInfo(Location location,String title){
            if(location != null) {
                LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(currentLocation).title(title));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation,10));
            }
        }
    >function to request permission from user
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
                    Location lastLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    locationInfo(lastLocation,"Your lastLocation");
                }

            }
        }

        private GoogleMap mMap;
        private ActivityMapsBinding binding;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            binding = ActivityMapsBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());

            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            Intent intent=getIntent();
            locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            locationListener=new LocationListener() {
                @Override
                public void onLocationChanged(@NonNull Location location) {
                    locationInfo(location,"Your Location");
                }
            };
>code to ask permission and check permission from user

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
            }else{

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
>code to find the last location and update the last location
                Location
        lastLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    locationInfo(lastLocation,"Your lastlocation");
            }

        }
    }

Body:
Its because you have move camera when your location update. You just need to put condition whether its user call or not to see current location.

Here is the line, this will alway move camera and display your current location

mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation,10));

You can do like this, whenever user required to see current location then change fromUser = true and then make to false back. Just like happen in Google Map when you click on location button.

var fromUser = false;

if(fromUser){
     mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation,10));
     fromUser = false;
}


问:
convert various source data_types schema to synapse data types schema mapping framework
In order to convert various source data_types to  Azure synapse data types to generate ddl so that data can be injected through a PySpark framework. For that I have to use the datatypes dictionary which contains distinct source data types mapped to synapse data types shown below as 'distinct_data_types_source2synapse'. But the actual columns list that I am getting from meta data is like a list of tuples shown below as 'column_list'. Need to find a way to convert source specific data type to synapse data type in columnist so that I can generate DDL to inject data in Azure synapse.

```<code>distinct_data_types_source2synapse = {
    'DATE': 'DATE',
    'PERIOD TIME': 'DATETIME',
    'NUMERIC': 'INT',
    'UROWID': 'VARCHAR',
    'DATETIME2': 'DATETIME2',
    'INTERVAL DAY TO MINUTE': '',
    'PERIOD TIMESTAMP': '',
    'BINARY': 'VARBINARY',
    'DECFLOAT': 'FLOAT',
    'DATETIME': 'DATETIME',
    'VARCHAR': 'VARCHAR' }

column_list = ['[profile_id] VARCHAR NOT NULL', '[age] NUMERIC NOT NULL', '[tenure] PERIOD TIME NULL']
</code>```

expected output columnlist as

```<code>['[profile_id] VARCHAR NOT NULL', '[age] INT NOT NULL', '[tenure] DATETIME NULL']
</code>```
```<code>import pandas as pd
import numpy as np
s=pd.Series(column_list)
for i in s:
  print(i.split())
  v= i.split()
  if v[1] in distinct_data_types_source2synapse keys():
    print("yes..change column type")
  else:
    print("no don't change")
</code>```

答:
```<code>
data_type_mapping = { 'DATE': 'DATE', 'PERIODTIME': 'DATETIME', 'NUMERIC': 'INT', 'UROWID': 'VARCHAR', 'DATETIME2': 'DATETIME2', 'INTERVAL DAY TO MINUTE': '', 'PERIOD TIMESTAMP': '', 'BINARY': 'VARBINARY', 'DECFLOAT': 'FLOAT', 'DATETIME': 'DATETIME', 'VARCHAR': 'VARCHAR' }

l = ['[profile_id] VARCHAR NOT NULL', '[age] NUMERIC NOT NULL', '[tenure] PERIODTIME NULL']

str = ""

for i in l:
    str += (i)
    str += (", ")

#print(str)

l1 = str.split(" ")
l2 = ([data_type_mapping.get(n, n) for n in l1])
print(' '.join(l2)[:-2])

</code>```
<p>#this would work perfectly, if there are no spaces in keys of the dictionary.</p>

Body:
In order to convert various source data_types to  Azure synapse data types to generate ddl so that data can be injected through a PySpark framework. For that I have to use the datatypes dictionary which contains distinct source data types mapped to synapse data types shown below as 'distinct_data_types_source2synapse'. But the actual columns list that I am getting from meta data is like a list of tuples shown below as 'column_list'. Need to find a way to convert source specific data type to synapse data type in columnist so that I can generate DDL to inject data in Azure synapse.

distinct_data_types_source2synapse = {
    'DATE': 'DATE',
    'PERIOD TIME': 'DATETIME',
    'NUMERIC': 'INT',
    'UROWID': 'VARCHAR',
    'DATETIME2': 'DATETIME2',
    'INTERVAL DAY TO MINUTE': '',
    'PERIOD TIMESTAMP': '',
    'BINARY': 'VARBINARY',
    'DECFLOAT': 'FLOAT',
    'DATETIME': 'DATETIME',
    'VARCHAR': 'VARCHAR' }

column_list = ['[profile_id] VARCHAR NOT NULL', '[age] NUMERIC NOT NULL', '[tenure] PERIOD TIME NULL']

expected output columnlist as

['[profile_id] VARCHAR NOT NULL', '[age] INT NOT NULL', '[tenure] DATETIME NULL']

import pandas as pd
import numpy as np
s=pd.Series(column_list)
for i in s:
  print(i.split())
  v= i.split()
  if v[1] in distinct_data_types_source2synapse keys():
    print("yes..change column type")
  else:
    print("no don't change")

Body:
data_type_mapping = { 'DATE': 'DATE', 'PERIODTIME': 'DATETIME', 'NUMERIC': 'INT', 'UROWID': 'VARCHAR', 'DATETIME2': 'DATETIME2', 'INTERVAL DAY TO MINUTE': '', 'PERIOD TIMESTAMP': '', 'BINARY': 'VARBINARY', 'DECFLOAT': 'FLOAT', 'DATETIME': 'DATETIME', 'VARCHAR': 'VARCHAR' }

l = ['[profile_id] VARCHAR NOT NULL', '[age] NUMERIC NOT NULL', '[tenure] PERIODTIME NULL']

str = ""

for i in l:
    str += (i)
    str += (", ")

#print(str)

l1 = str.split(" ")
l2 = ([data_type_mapping.get(n, n) for n in l1])
print(' '.join(l2)[:-2])

#this would work perfectly, if there are no spaces in keys of the dictionary.


问:
is driver.getContextHandles() or driver.context() removed in Selenium4 as these methods are coming for Appium driver?
Is driver.getContextHandles()  or driver.context() removed in Selenium4 as these methods are coming for Appium driver?
I am Using Selenium 4.1.1 and JavaClient- 8.0.0-beta2.

Facing issue to find element while running a test in Hybrind app.
Scenario
A Web view is opening in App post click of an icon. Element not found exception is coming whereas element is uniquely found/identified in Chrome.

Any suggestions in this will help to procced further.

答:
Regarding the question about driver.context()

This moved to io.appium.java_client.remote.SupportsContextSwitching interface which also includes the default implementation.

In your tests if you're using AppiumDriver, just cast the driver, like:

```<code>io.appium.java_client.remote.SupportsContextSwitching

((SupportsContextSwitching) driver).getContextHandles();
</code>```

NOTE: To have this work without ClassCastException, the driver initially should be created as AndroidDriver or IOSDriver, e.g.:

```<code>BaseOptions options = new UiAutomator2Options().setAutoGrantPermissions(true);
AppiumDriver driver = new AndroidDriver(new URL("http://localhost:4723/wd/hub"), options);
</code>```

More Details

I mention this, because driver.context() is a special case of a larger context.

There are a lot of changes in appium java client version 8 from version 7.

One of them: A lot of platform-specific and not defined by W3C WebDriver standard methods moved out to additional interfaces.

So pure AppiumDriver doesn't have this methods.

But if we look throught the code, e.g. to AndroidDriver, we see it implements 20+ additional interfaces:

```<code>public class AndroidDriver extends AppiumDriver implements
        PressesKey,
        SupportsRotation,
        SupportsContextSwitching,
        SupportsLocation,
        PerformsTouchActions,
        HidesKeyboard,
        HasDeviceTime,
        ...
</code>```

and the same for IOSDriver.

If you cannot find some method in AppiumDriver, try to go throught the interfaces, which AndroidDriver/ IOSDriver are implementing.

Body:
Regarding the question about driver.context()

This moved to io.appium.java_client.remote.SupportsContextSwitching interface which also includes the default implementation.

In your tests if you're using AppiumDriver, just cast the driver, like:

io.appium.java_client.remote.SupportsContextSwitching

((SupportsContextSwitching) driver).getContextHandles();

NOTE: To have this work without ClassCastException, the driver initially should be created as AndroidDriver or IOSDriver, e.g.:

BaseOptions options = new UiAutomator2Options().setAutoGrantPermissions(true);
AppiumDriver driver = new AndroidDriver(new URL("http://localhost:4723/wd/hub"), options);

More Details

I mention this, because driver.context() is a special case of a larger context.

There are a lot of changes in appium java client version 8 from version 7.

One of them: A lot of platform-specific and not defined by W3C WebDriver standard methods moved out to additional interfaces.

So pure AppiumDriver doesn't have this methods.

But if we look throught the code, e.g. to AndroidDriver, we see it implements 20+ additional interfaces:

public class AndroidDriver extends AppiumDriver implements
        PressesKey,
        SupportsRotation,
        SupportsContextSwitching,
        SupportsLocation,
        PerformsTouchActions,
        HidesKeyboard,
        HasDeviceTime,
        ...

and the same for IOSDriver.

If you cannot find some method in AppiumDriver, try to go throught the interfaces, which AndroidDriver/ IOSDriver are implementing.


问:
FileStream, read data chunk from big file. Filesize bigger than int. How to set the offset?
FileStream.Read() is defined as:

```<code>public override int Read(
    byte[] array,
    int offset,
    int count
)
</code>```

How can I read some bytes from an offset bigger than int.MaxValue?

Let's say I have a very big file and I want to read 100MB starting from position 3147483648.

How can I do that?

答:
The offset here is the offset in the array at which to start writing. In your case, just set:

```<code>stream.Position = 3147483648;
</code>```

and then use Read(). The offset is most commonly used when you know you need to read [n] bytes:

```<code>int toRead = 20, bytesRead;
while(toRead > 0 && (bytesRead = stream.Read(buffer, offset, toRead)) > 0)
{
    toRead -= bytesRead;
    offset += bytesRead;
}
if(toRead > 0) throw new EndOfStreamException();
</code>```

this will read exactly 20 bytes into buffer (or throw an exception). Note that Read() is not guaranteed to read all the required data in one go, hence a loop incrementing an offset is usually required.

ContentLicense: CC BY-SA 3.0

Body:
FileStream.Read() is defined as:

public override int Read(
    byte[] array,
    int offset,
    int count
)

How can I read some bytes from an offset bigger than int.MaxValue?

Let's say I have a very big file and I want to read 100MB starting from position 3147483648.

How can I do that?

Body:
The offset here is the offset in the array at which to start writing. In your case, just set:

stream.Position = 3147483648;

and then use Read(). The offset is most commonly used when you know you need to read [n] bytes:

int toRead = 20, bytesRead;
while(toRead > 0 && (bytesRead = stream.Read(buffer, offset, toRead)) > 0)
{
    toRead -= bytesRead;
    offset += bytesRead;
}
if(toRead > 0) throw new EndOfStreamException();

this will read exactly 20 bytes into buffer (or throw an exception). Note that Read() is not guaranteed to read all the required data in one go, hence a loop incrementing an offset is usually required.


问:
Why does GitLab not show merge pipeline anymore in MR?
Until now I had my whole GitLab configuration placed inside .gitlab-ci.yml. The configuration looked as follows:

.gitlab-ci.yml

```<code>image: ...

.deploy-default:
  stage: deploy
  tags:
    - docker
  script:
    ...

.rules_mr_or_branch_manual:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      when: manual
    - if: '$CI_COMMIT_BRANCH'
      when: manual

.rules_mr_or_commit_not_master_not_release:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_COMMIT_REF_NAME != "master" && $CI_COMMIT_REF_NAME != "release"'
      allow_failure: false
    - if: '$CI_COMMIT_BRANCH && $CI_COMMIT_REF_NAME != "master" && $CI_COMMIT_REF_NAME != "release"'
      when: manual
      allow_failure: true

.build_default:
  stage: build
  tags:
    - docker
  script:
    ...

stages:
  - test
  - build
  - deploy
  - post-deploy

build-production:
  extends:
    - .build_default
  environment:
    name: production
  interruptible: true
  rules:
    - if: '$CI_PIPELINE_SOURCE == "pipeline"'
      when: never
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_COMMIT_REF_NAME == "release"'
      allow_failure: false
    - if: '$CI_COMMIT_BRANCH == "release"'
      allow_failure: false

build-staging:
  extends:
    - .build_default
  environment:
    name: staging
  rules:
    - if: '$CI_PIPELINE_SOURCE == "pipeline"'
      when: never
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_COMMIT_REF_NAME == "master"'
      allow_failure: false
    - if: '$CI_COMMIT_BRANCH == "master"'
      allow_failure: false

build-test:
  extends:
    - .build_default
    - .rules_mr_or_commit_not_master_not_release
  environment:
    name: test

# Test jobs
test-unit:
  stage: test
  tags:
    - test
  script:
    - yarn install && yarn test:unit
  coverage: /All\sfiles.*?\s+(\d+.\d+)/
  artifacts:
    reports:
      cobertura: coverage/cobertura-coverage.xml
  allow_failure: false
  rules:
    - if: '$CI_PIPELINE_SOURCE == "pipeline"'
      when: never
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      allow_failure: false
    - if: '$CI_COMMIT_REF_NAME == "master" || $CI_COMMIT_REF_NAME == "release"'
      allow_failure: false
    - if: '$CI_COMMIT_BRANCH'
      when: manual
      allow_failure: true

# Deploy jobs
deploy-test:
  extends:
    - .deploy-default
    - .rules_mr_or_branch_manual
  environment:
    name: test
  allow_failure: true

deploy-staging:
  extends:
    - .deploy-default
  environment:
    name: staging
  only:
    refs:
      - master
    variables:
      - $CI_PIPELINE_SOURCE != "pipeline"

deploy-production:
  extends:
    - .deploy-default
  environment:
    name: production
  interruptible: false
  allow_failure: false
  only:
    refs:
      - release
</code>```

Since it is planned to further extend the configuration with more jobs in near future, I thought I need to refactor my config in a way that it will stay readable even if many more jobs are added. For that reason, I split my config into several files, and furthermore, I rewrote my rules. I created a rule set to be able to reuse them in several jobs, and I used workflow to set rules which are applied globally. The result of the refactoring process looks as follows:

.gitlab-ci.yml

```<code>image: ...

include:
  - local: '/.gitlab/variables.yml'
  - local: '/.gitlab/rules.yml'
  - local: '/.gitlab/workflows.yml'
  - local: '/.gitlab/stages/test.yml'
  - local: '/.gitlab/stages/build.yml'
  - local: '/.gitlab/stages/deploy.yml'

stages:
  - test
  - build
  - deploy
</code>```

.gitlab/variables.yml

```<code>variables:
  STAGING_BRANCH_NAME: $STAGING_BRANCH_NAME
  PRODUCTION_BRANCH_NAME: $PRODUCTION_BRANCH_NAME
</code>```

.gitlab/rules.yml

```<code>.rule_references:
  pipeline__skip:
    if: '$CI_PIPELINE_SOURCE == "pipeline"'
    when: never
  mr:
    if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
  mr_staging:
    if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_COMMIT_REF_NAME == $STAGING_BRANCH_NAME'
  mr_production:
    if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_COMMIT_REF_NAME == $PRODUCTION_BRANCH_NAME'
  mr_staging_or_production:
    if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_COMMIT_REF_NAME == $STAGING_BRANCH_NAME || $CI_COMMIT_REF_NAME == $PRODUCTION_BRANCH_NAME)'
  mr_not_staging_not_production:
    if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_COMMIT_REF_NAME != $STAGING_BRANCH_NAME && $CI_COMMIT_REF_NAME != $PRODUCTION_BRANCH_NAME)'
  mr_not_staging_not_production__manual:
    if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_COMMIT_REF_NAME != $STAGING_BRANCH_NAME && $CI_COMMIT_REF_NAME != $PRODUCTION_BRANCH_NAME)'
    when: manual
    allow_failure: true
  commit_staging:
    if: '$CI_COMMIT_BRANCH == $STAGING_BRANCH_NAME'
  commit_production:
    if: '$CI_COMMIT_BRANCH == $PRODUCTION_BRANCH_NAME'
  commit_staging_or_production:
    if: '$CI_COMMIT_REF_NAME == $STAGING_BRANCH_NAME || $CI_COMMIT_REF_NAME == $PRODUCTION_BRANCH_NAME'
  commit_branch_with_open_mr__skip:
    if: '$CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS'
    when: never
</code>```

.gitlab/workflows

```<code>workflow:
  rules:
    - !reference [.rule_references, mr]
    - !reference [.rule_references, commit_branch_with_open_mr__skip]
    - !reference [.rule_references, commit_staging_or_production]
</code>```

.gitlab/stages/test.yml

```<code>test-unit:
  stage: test
  needs: []
  tags:
    - test
  script:
    - |
      echo "using SUB_DOMAIN_TEST SUB_DOMAIN_TEST"
    - yarn install --frozen-lockfile && yarn test:unit --silent
  coverage: /All\sfiles.*?\s+(\d+.\d+)/
  artifacts:
    when: always
    paths:
      - coverage/
    reports:
      cobertura: coverage/cobertura-coverage.xml
      junit: reports/junit.xml
  rules:
    - !reference [.rule_references, pipeline__skip]
    - !reference [.rule_references, mr]
    - !reference [.rule_references, commit_staging_or_production]
</code>```

.gitlab/stages/build.yml

```<code>.build_default:
  stage: build
  needs: ['test-unit']
  tags:
    - docker
  script:
    ...

build-test:
  extends:
    - .build_default
  environment:
    name: test
  rules:
    - !reference [.rule_references, mr_not_staging_not_production]

build-staging:
  extends:
    - .build_default
  environment:
    name: staging
  rules:
    - !reference [.rule_references, pipeline__skip]
    - !reference [.rule_references, mr_staging]
    - !reference [.rule_references, commit_staging]

build-production:
  extends:
    - .build_default
  environment:
    name: production
  rules:
    - !reference [.rule_references, pipeline__skip]
    - !reference [.rule_references, mr_production]
    - !reference [.rule_references, commit_production]
</code>```

.gitlab/stages/deploy.yml

```<code>.deploy-default:
  stage: deploy
  tags:
    - docker
  interruptible: true
  script:
    ...

deploy-test:
  needs: ['build-test']
  extends:
    - .deploy-default
  environment:
    name: test
  rules:
    - !reference [.rule_references, mr_not_staging_not_production__manual]

deploy-staging:
  needs: ['build-staging']
  extends:
    - .deploy-default
  environment:
    name: staging
  rules:
    - !reference [.rule_references, pipeline__skip]
    - !reference [.rule_references, mr_staging]
    - !reference [.rule_references, commit_staging]

deploy-production:
  needs: ['build-production']
  extends:
    - .deploy-default
  environment:
    name: production
  interruptible: false
  rules:
    - !reference [.rule_references, pipeline__skip]
    - !reference [.rule_references, mr_production]
    - !reference [.rule_references, commit_production]
</code>```

Before I applied all those changes my MRs looked as follows:

But after I did all the refactoring my MRs look this way (missing the merge pipeline below the test widget):

However, the merge pipeline is created, running, and successful which can be observed in GitLab CI/CD - Pipelines, but it is just not displayed in MRs. Furthermore, when I look into the commit list of master or release branches in GitLab, they are missing the green check icon (pipeline passed) linking to the related pipeline. This also causes the pipeline badge to just show "pipeline unknown".

I suppose that the problem is related to my ruleset, the assignment of the rules to the jobs, and/or the assignment of the rules to workflow. However, I have no clue what to change.

I appreciate you help.

Update:

I forked the project for trying out some rule changes that might fix the issue. I recognized the issue does not occur in the forked project. I recognized that in the original project the merge commit is not assigned to master but rather to the merge request:

In contrast in the forked project, the merge commit is assigned to the master branch:

There is also a different icon displayed.

Both projects have the same ruleset and I could not find any differences in the settings.

I have no idea why this happens.

答:
I found the cause of the issue. The behavior observed above happens only if I have an open merge request (from a feature branch into the master branch) and at the same time another open merge request (from the master branch into the release branch). When the feature branch is now merged into the master branch a pipeline is created and run only for the still open MR (master branch into release branch) and not for the master branch since my rules define “don’t create a pipeline for branches with open MR”. Actually, this behavior is correct because I don’t want duplicate pipelines (as explained in Worfklow - Switch between branch pipelines and merge request pipelines).

The problem is, however, that my project’s badge (based on master branch) is showing “pipeline unknown” status now, since the pipeline is a merge request pipeline assigned to the open merge request (master branch into release branch) and not a commit pipeline assigned to the merge commit on master.

If I created duplicate pipelines (a merge request pipeline and a branch pipeline), this problem would not occur. However, it remains unclear to me if it is intended by GitLab that I need duplicate pipelines just to get the pipeline badge showing the correct status (passed or failed instead of unknown). Furthermore, I thought it would be great if GitLab would also display an info text that due to the other open MR only a pipeline in the open MR was created, because otherwise if users don’t switch to CI/CD - Pipelines or to the open merge request (master into release), they might be confused and assume that no pipeline runs on merge, as it happened to me.

Body:
Until now I had my whole GitLab configuration placed inside .gitlab-ci.yml. The configuration looked as follows:

.gitlab-ci.yml

image: ...

.deploy-default:
  stage: deploy
  tags:
    - docker
  script:
    ...

.rules_mr_or_branch_manual:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      when: manual
    - if: '$CI_COMMIT_BRANCH'
      when: manual

.rules_mr_or_commit_not_master_not_release:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_COMMIT_REF_NAME != "master" && $CI_COMMIT_REF_NAME != "release"'
      allow_failure: false
    - if: '$CI_COMMIT_BRANCH && $CI_COMMIT_REF_NAME != "master" && $CI_COMMIT_REF_NAME != "release"'
      when: manual
      allow_failure: true

.build_default:
  stage: build
  tags:
    - docker
  script:
    ...

stages:
  - test
  - build
  - deploy
  - post-deploy

build-production:
  extends:
    - .build_default
  environment:
    name: production
  interruptible: true
  rules:
    - if: '$CI_PIPELINE_SOURCE == "pipeline"'
      when: never
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_COMMIT_REF_NAME == "release"'
      allow_failure: false
    - if: '$CI_COMMIT_BRANCH == "release"'
      allow_failure: false

build-staging:
  extends:
    - .build_default
  environment:
    name: staging
  rules:
    - if: '$CI_PIPELINE_SOURCE == "pipeline"'
      when: never
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_COMMIT_REF_NAME == "master"'
      allow_failure: false
    - if: '$CI_COMMIT_BRANCH == "master"'
      allow_failure: false

build-test:
  extends:
    - .build_default
    - .rules_mr_or_commit_not_master_not_release
  environment:
    name: test

# Test jobs
test-unit:
  stage: test
  tags:
    - test
  script:
    - yarn install && yarn test:unit
  coverage: /All\sfiles.*?\s+(\d+.\d+)/
  artifacts:
    reports:
      cobertura: coverage/cobertura-coverage.xml
  allow_failure: false
  rules:
    - if: '$CI_PIPELINE_SOURCE == "pipeline"'
      when: never
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      allow_failure: false
    - if: '$CI_COMMIT_REF_NAME == "master" || $CI_COMMIT_REF_NAME == "release"'
      allow_failure: false
    - if: '$CI_COMMIT_BRANCH'
      when: manual
      allow_failure: true

# Deploy jobs
deploy-test:
  extends:
    - .deploy-default
    - .rules_mr_or_branch_manual
  environment:
    name: test
  allow_failure: true

deploy-staging:
  extends:
    - .deploy-default
  environment:
    name: staging
  only:
    refs:
      - master
    variables:
      - $CI_PIPELINE_SOURCE != "pipeline"

deploy-production:
  extends:
    - .deploy-default
  environment:
    name: production
  interruptible: false
  allow_failure: false
  only:
    refs:
      - release

Since it is planned to further extend the configuration with more jobs in near future, I thought I need to refactor my config in a way that it will stay readable even if many more jobs are added. For that reason, I split my config into several files, and furthermore, I rewrote my rules. I created a rule set to be able to reuse them in several jobs, and I used workflow to set rules which are applied globally. The result of the refactoring process looks as follows:

.gitlab-ci.yml

image: ...

include:
  - local: '/.gitlab/variables.yml'
  - local: '/.gitlab/rules.yml'
  - local: '/.gitlab/workflows.yml'
  - local: '/.gitlab/stages/test.yml'
  - local: '/.gitlab/stages/build.yml'
  - local: '/.gitlab/stages/deploy.yml'

stages:
  - test
  - build
  - deploy

.gitlab/variables.yml

variables:
  STAGING_BRANCH_NAME: $STAGING_BRANCH_NAME
  PRODUCTION_BRANCH_NAME: $PRODUCTION_BRANCH_NAME

.gitlab/rules.yml

.rule_references:
  pipeline__skip:
    if: '$CI_PIPELINE_SOURCE == "pipeline"'
    when: never
  mr:
    if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
  mr_staging:
    if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_COMMIT_REF_NAME == $STAGING_BRANCH_NAME'
  mr_production:
    if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_COMMIT_REF_NAME == $PRODUCTION_BRANCH_NAME'
  mr_staging_or_production:
    if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_COMMIT_REF_NAME == $STAGING_BRANCH_NAME || $CI_COMMIT_REF_NAME == $PRODUCTION_BRANCH_NAME)'
  mr_not_staging_not_production:
    if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_COMMIT_REF_NAME != $STAGING_BRANCH_NAME && $CI_COMMIT_REF_NAME != $PRODUCTION_BRANCH_NAME)'
  mr_not_staging_not_production__manual:
    if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_COMMIT_REF_NAME != $STAGING_BRANCH_NAME && $CI_COMMIT_REF_NAME != $PRODUCTION_BRANCH_NAME)'
    when: manual
    allow_failure: true
  commit_staging:
    if: '$CI_COMMIT_BRANCH == $STAGING_BRANCH_NAME'
  commit_production:
    if: '$CI_COMMIT_BRANCH == $PRODUCTION_BRANCH_NAME'
  commit_staging_or_production:
    if: '$CI_COMMIT_REF_NAME == $STAGING_BRANCH_NAME || $CI_COMMIT_REF_NAME == $PRODUCTION_BRANCH_NAME'
  commit_branch_with_open_mr__skip:
    if: '$CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS'
    when: never

.gitlab/workflows

workflow:
  rules:
    - !reference [.rule_references, mr]
    - !reference [.rule_references, commit_branch_with_open_mr__skip]
    - !reference [.rule_references, commit_staging_or_production]

.gitlab/stages/test.yml

test-unit:
  stage: test
  needs: []
  tags:
    - test
  script:
    - |
      echo "using SUB_DOMAIN_TEST SUB_DOMAIN_TEST"
    - yarn install --frozen-lockfile && yarn test:unit --silent
  coverage: /All\sfiles.*?\s+(\d+.\d+)/
  artifacts:
    when: always
    paths:
      - coverage/
    reports:
      cobertura: coverage/cobertura-coverage.xml
      junit: reports/junit.xml
  rules:
    - !reference [.rule_references, pipeline__skip]
    - !reference [.rule_references, mr]
    - !reference [.rule_references, commit_staging_or_production]

.gitlab/stages/build.yml

.build_default:
  stage: build
  needs: ['test-unit']
  tags:
    - docker
  script:
    ...

build-test:
  extends:
    - .build_default
  environment:
    name: test
  rules:
    - !reference [.rule_references, mr_not_staging_not_production]

build-staging:
  extends:
    - .build_default
  environment:
    name: staging
  rules:
    - !reference [.rule_references, pipeline__skip]
    - !reference [.rule_references, mr_staging]
    - !reference [.rule_references, commit_staging]

build-production:
  extends:
    - .build_default
  environment:
    name: production
  rules:
    - !reference [.rule_references, pipeline__skip]
    - !reference [.rule_references, mr_production]
    - !reference [.rule_references, commit_production]

.gitlab/stages/deploy.yml

.deploy-default:
  stage: deploy
  tags:
    - docker
  interruptible: true
  script:
    ...

deploy-test:
  needs: ['build-test']
  extends:
    - .deploy-default
  environment:
    name: test
  rules:
    - !reference [.rule_references, mr_not_staging_not_production__manual]

deploy-staging:
  needs: ['build-staging']
  extends:
    - .deploy-default
  environment:
    name: staging
  rules:
    - !reference [.rule_references, pipeline__skip]
    - !reference [.rule_references, mr_staging]
    - !reference [.rule_references, commit_staging]

deploy-production:
  needs: ['build-production']
  extends:
    - .deploy-default
  environment:
    name: production
  interruptible: false
  rules:
    - !reference [.rule_references, pipeline__skip]
    - !reference [.rule_references, mr_production]
    - !reference [.rule_references, commit_production]

Before I applied all those changes my MRs looked as follows:

But after I did all the refactoring my MRs look this way (missing the merge pipeline below the test widget):

However, the merge pipeline is created, running, and successful which can be observed in GitLab CI/CD - Pipelines, but it is just not displayed in MRs. Furthermore, when I look into the commit list of master or release branches in GitLab, they are missing the green check icon (pipeline passed) linking to the related pipeline. This also causes the pipeline badge to just show "pipeline unknown".

I suppose that the problem is related to my ruleset, the assignment of the rules to the jobs, and/or the assignment of the rules to workflow. However, I have no clue what to change.

I appreciate you help.

Update:

I forked the project for trying out some rule changes that might fix the issue. I recognized the issue does not occur in the forked project. I recognized that in the original project the merge commit is not assigned to master but rather to the merge request:

In contrast in the forked project, the merge commit is assigned to the master branch:

There is also a different icon displayed.

Both projects have the same ruleset and I could not find any differences in the settings.

I have no idea why this happens.


问:
SEQUELIZE: How to use EXTRACT MySQL function
Let's say I'm trying to extract YEAR_MONTH from the records in the user table

I can write:

```<code>SELECT EXTRACT(YEAR_MONTH FROM u.created_on)
FROM user u;
</code>```

I am struggling to understand how to write a sequelize query that involves more complex MySQL methods.

I know I can use something like:

sequelize.fn('avg', sequelize.col('User.age')), 'avg_age']

for simple MySQL methods that take only one parameter.

This has been the closest I can get:

```<code>[sequelize.fn('extract', ['YEAR', 'FROM'],
 sequelize.col('User.created_on')), 'created_year_month']
</code>```

Which results in the following SQL:

```<code>extract('YEAR_MONTH', 'FROM', `User`.`created_on`) AS `created_year_month`
</code>```

as opposed to

```<code>SELECT EXTRACT(YEAR_MONTH FROM u.created_on)
FROM user u;
</code>```

I am at a loss as to how I can properly build this query.

答:
```<code>const tasks = await Task.findAll({
  attributes: ['id',

    [ sequelize.literal('extract(year from "Task"."created_at"::timestamp)'), 'year']

]})
</code>```

Body:
Let's say I'm trying to extract YEAR_MONTH from the records in the user table

I can write:

SELECT EXTRACT(YEAR_MONTH FROM u.created_on)
FROM user u;

I am struggling to understand how to write a sequelize query that involves more complex MySQL methods.

I know I can use something like:

sequelize.fn('avg', sequelize.col('User.age')), 'avg_age']

for simple MySQL methods that take only one parameter.

This has been the closest I can get:

[sequelize.fn('extract', ['YEAR', 'FROM'],
 sequelize.col('User.created_on')), 'created_year_month']

Which results in the following SQL:

extract('YEAR_MONTH', 'FROM', `User`.`created_on`) AS `created_year_month`

as opposed to

SELECT EXTRACT(YEAR_MONTH FROM u.created_on)
FROM user u;

I am at a loss as to how I can properly build this query.


问:
Asp.Net Core-Use authentication for two users with two different timspan?
I put a configuration authentication for all users in the startup file,Is it possible to set a config for a specific roll with a different time?

Config :

```<code> services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie(options =>
        {
            options.LoginPath = "/LoginUser"; //"/Home/Index"
            options.LogoutPath = "/SignOut";
            options.ExpireTimeSpan = TimeSpan.FromMinutes(43200); // 1 month
        });
</code>```

Do I want to design a separate login form for the admin and use custom authentication?

答:
ExpiresUtc setting helps you to set an absolute expiration to cookie. This settings overrides ExpireTimeSpan setting value.
You could set it in your controller to set differenet timespan for differenet users</p>
```<code>public async Task<IActionResult> Login(LoginViewModel loginvm)
  {
              .......
             var time = Time(loginvm.user);
              await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPricipal, new AuthenticationProperties
                        {
                            ExpiresUtc = DateTime.UtcNow.AddMinutes(time),
                            IsPersistent = false,
                            AllowRefresh = false
                        });
                . .......
        }

    public double Time(User user)
            {
                double time = 0;
                if(user.Name=="J")
                {
                    time = 1;
                }
                else
               {
                    .......
               }

                return time;
            }
</code>```

Body:
I put a configuration authentication for all users in the startup file,Is it possible to set a config for a specific roll with a different time?

Config :

 services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie(options =>
        {
            options.LoginPath = "/LoginUser"; //"/Home/Index"
            options.LogoutPath = "/SignOut";
            options.ExpireTimeSpan = TimeSpan.FromMinutes(43200); // 1 month
        });

Do I want to design a separate login form for the admin and use custom authentication?

Body:
ExpiresUtc setting helps you to set an absolute expiration to cookie. This settings overrides ExpireTimeSpan setting value.
You could set it in your controller to set differenet timespan for differenet users

public async Task<IActionResult> Login(LoginViewModel loginvm)
  {
              .......
             var time = Time(loginvm.user);
              await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPricipal, new AuthenticationProperties
                        {
                            ExpiresUtc = DateTime.UtcNow.AddMinutes(time),
                            IsPersistent = false,
                            AllowRefresh = false
                        });
                . .......
        }

    public double Time(User user)
            {
                double time = 0;
                if(user.Name=="J")
                {
                    time = 1;
                }
                else
               {
                    .......
               }

                return time;
            }


问:
Are margin and padding only applied to layout and element respectively?
I’m a UX designer and currently working on WYSIWYG editor. I was wondering if this structure (displayed in the image) correct?

If so, are margin and padding only applied to layout and element respectively? If so, there wouldn’t be a scenario where padding is applied to a layout?

答:
In each design, each element is considered as a box
And each design is a set of boxes that are placed next to each other.
Each box consists of an interior space and a border and an outer space.
Each box can be spaced from adjacent boxes
This distance is applied to the box with the Margin feature
The Border of each box can be spaced from its contents, which is applied with padding.
Note: All elements can have borders and pads.</p>


问:
Cookies not sent with cross-origin-request
After days of searching and trying, I'm here now.

I deployed the React Application in Netlify and the Node.js backend in Heroku. Everything works fine in localhost environment. But after deploying, cookies are not sent in request header.

CORS:(Backend Node.js)

```<code>app.use(cors({
  origin: CORS_ORIGIN,
  credentials: true,
  allowedHeaders: "Content-Type,Accept,User-Agent,Accept-Language,Access-Control-Allow-Origin,Access-Control-Allow-Credentials,cache-control"
}));
</code>```

Axios:

```<code>import axios from "axios";
axios.defaults.withCredentials = true;
export default axios.create({
   baseURL: process.env.REACT_APP_BACKEND + "/api",
   headers: {
      "Content-type": "application/json",
      "Access-Control-Allow-Origin": process.env.REACT_APP_BACKEND,
   },
});
</code>```

Fetching Data(Mutation): apiClient is imported from above Axios.js and cookies is handled by react-cookies

```<code>apiClient.post("/auth/login",{ email: "name@mail.com", password: "pawspaws" })
    .then((res) => {
            setCookie("jwt", res.data.accessToken, { path: process.env.REACT_APP_PATH || "/", domain: process.env.REACT_APP_DOMAIN, maxAge: 26000, secure: true, sameSite: 'None' });
            setCookie("refresh", res.data.refreshToken, { path: process.env.REACT_APP_PATH || "/", domain: process.env.REACT_APP_DOMAIN, maxAge: 2600000, secure: true, sameSite: 'None' });
            setCookie("user", res.data.user, { path: process.env.REACT_APP_PATH || "/", domain: process.env.REACT_APP_DOMAIN, maxAge: 26000, secure: true, sameSite: 'None' });
         }).catch((err) => console.log(err.response))
</code>```

Above code sets the cookies.. and it's working.

Now, below is the request I'm sending which doesn't send the Cookies along with the request:

```<code>apiClient.get("/posts/timeline", { params: { email: "name@mail.com" } })
         .then((res) => { console.log(res.data); })
         .catch((err) => { console.log(err.response) });
</code>```

Well, it returns unauthorized since the Cookie is not sent at all..

答:
Ok, i found my own solution.. It was pretty easy.. It was setting up proxy

Just added line below to package.json in frontend:

```<code>"proxy":"https://random.name.herokuapp.com",
</code>```

FYI, for Netlify, we need additional _redirects file in public folder.

_redirects

```<code>/api/* https://random.name.herokuapp.com/api/:splat 200
/*     /index.html                                  200
</code>```

Body:
After days of searching and trying, I'm here now.

I deployed the React Application in Netlify and the Node.js backend in Heroku. Everything works fine in localhost environment. But after deploying, cookies are not sent in request header.

CORS:(Backend Node.js)

app.use(cors({
  origin: CORS_ORIGIN,
  credentials: true,
  allowedHeaders: "Content-Type,Accept,User-Agent,Accept-Language,Access-Control-Allow-Origin,Access-Control-Allow-Credentials,cache-control"
}));

Axios:

import axios from "axios";
axios.defaults.withCredentials = true;
export default axios.create({
   baseURL: process.env.REACT_APP_BACKEND + "/api",
   headers: {
      "Content-type": "application/json",
      "Access-Control-Allow-Origin": process.env.REACT_APP_BACKEND,
   },
});

Fetching Data(Mutation): apiClient is imported from above Axios.js and cookies is handled by react-cookies

apiClient.post("/auth/login",{ email: "name@mail.com", password: "pawspaws" })
    .then((res) => {
            setCookie("jwt", res.data.accessToken, { path: process.env.REACT_APP_PATH || "/", domain: process.env.REACT_APP_DOMAIN, maxAge: 26000, secure: true, sameSite: 'None' });
            setCookie("refresh", res.data.refreshToken, { path: process.env.REACT_APP_PATH || "/", domain: process.env.REACT_APP_DOMAIN, maxAge: 2600000, secure: true, sameSite: 'None' });
            setCookie("user", res.data.user, { path: process.env.REACT_APP_PATH || "/", domain: process.env.REACT_APP_DOMAIN, maxAge: 26000, secure: true, sameSite: 'None' });
         }).catch((err) => console.log(err.response))

Above code sets the cookies.. and it's working.

Now, below is the request I'm sending which doesn't send the Cookies along with the request:

apiClient.get("/posts/timeline", { params: { email: "name@mail.com" } })
         .then((res) => { console.log(res.data); })
         .catch((err) => { console.log(err.response) });

Well, it returns unauthorized since the Cookie is not sent at all..

Body:
Ok, i found my own solution.. It was pretty easy.. It was setting up proxy

Just added line below to package.json in frontend:

"proxy":"https://random.name.herokuapp.com",

FYI, for Netlify, we need additional _redirects file in public folder.

_redirects

/api/* https://random.name.herokuapp.com/api/:splat 200
/*     /index.html                                  200


问:
interface contains type constraints: cannot use interface in conversion

type Number interface {
    int | int64 | float64
}

type NNumber interface {
}

//interface contains type constraints
//type NumberSlice []Number

type NNumberSlice []NNumber

func main() {
    var b interface{}
    b = interface{}(1)
    fmt.Println(b)

    // interface contains type constraints
    // cannot use interface Number in conversion (contains specific type constraints or is comparable)
    //a := []Number{Number(1), Number(2), Number(3), Number(4)}
    //fmt.Println(a)

    aa := []interface{}{interface{}(1), interface{}(2), interface{}(3), 4}
    fmt.Println(aa)

    aaa := []NNumber{NNumber(1), NNumber(2), NNumber(3), 4}
    fmt.Println(aaa)
}
```

why the Number slice a couldn't be initialized like that?

NumberSlice and NNumberSlice look like similarly, but what mean type constraints, it looks strange grammar

答:
The language specifications explicitly disallow using interfaces with  type elements as anything other than type parameter constraints (the quote is under the paragraph Interface types):

Interfaces that are not basic may only be used as type constraints, or as elements of other interfaces used as constraints. They cannot be the types of values or variables, or components of other, non-interface types.

An interface that embeds comparable or another non-basic interface is also non-basic. Your Number interface contains a union, hence it is non-basic too.

A few examples:

```<code>// basic: only methods
type A1 interface {
    GetName() string
}

// basic: only methods and/or embeds basic interface
type B1 interface {
    A1
    SetValue(v int)
}

// non-basic: embeds comparable
type Message interface {
    comparable
    Content() string
}

// non-basic: has a type element (union)
type Number interface {
    int | int64 | float64
}

// non-basic: embeds a non-basic interface
type SpecialNumber interface {
    Number
    IsSpecial() bool
}
</code>```

In the initialization of the variable a, you are attempting to use Number in a type conversion Number(1), and this is not allowed.

You can only use Number as a type parameter constraint, i.e. to restrict the types allowed for instantiation of a generic type or function. For example:

```<code>type Coordinates[T Number] struct {
    x, y T
}

func sum[T Number](a, b T) T {
    return a + b
}
</code>```

Body:
type Number interface {
    int | int64 | float64
}

type NNumber interface {
}

//interface contains type constraints
//type NumberSlice []Number

type NNumberSlice []NNumber

func main() {
    var b interface{}
    b = interface{}(1)
    fmt.Println(b)

    // interface contains type constraints
    // cannot use interface Number in conversion (contains specific type constraints or is comparable)
    //a := []Number{Number(1), Number(2), Number(3), Number(4)}
    //fmt.Println(a)

    aa := []interface{}{interface{}(1), interface{}(2), interface{}(3), 4}
    fmt.Println(aa)

    aaa := []NNumber{NNumber(1), NNumber(2), NNumber(3), 4}
    fmt.Println(aaa)
}

why the Number slice a couldn't be initialized like that?

NumberSlice and NNumberSlice look like similarly, but what mean type constraints, it looks strange grammar

Body:
The language specifications explicitly disallow using interfaces with  type elements as anything other than type parameter constraints (the quote is under the paragraph Interface types):

Interfaces that are not basic may only be used as type constraints, or as elements of other interfaces used as constraints. They cannot be the types of values or variables, or components of other, non-interface types.

An interface that embeds comparable or another non-basic interface is also non-basic. Your Number interface contains a union, hence it is non-basic too.

A few examples:

// basic: only methods
type A1 interface {
    GetName() string
}

// basic: only methods and/or embeds basic interface
type B1 interface {
    A1
    SetValue(v int)
}

// non-basic: embeds comparable
type Message interface {
    comparable
    Content() string
}

// non-basic: has a type element (union)
type Number interface {
    int | int64 | float64
}

// non-basic: embeds a non-basic interface
type SpecialNumber interface {
    Number
    IsSpecial() bool
}

In the initialization of the variable a, you are attempting to use Number in a type conversion Number(1), and this is not allowed.

You can only use Number as a type parameter constraint, i.e. to restrict the types allowed for instantiation of a generic type or function. For example:

type Coordinates[T Number] struct {
    x, y T
}

func sum[T Number](a, b T) T {
    return a + b
}


问:
Detect click on text in contenteditable div
I would like to allow editing of text when actual text is clicked. The rest of the white space I need for a dragging functionality.

Is there any way to detect when mouse clicks on text instead of white space in a contenteditable div?

Is there maybe some CSS I can add to a div that would wrap around the text and not the whitespace? Or is there some Javascript that can tell when user clicked on text.

```<code>      <div class="container">
        <div class="textbox" contenteditable="true"></div>
      </div>
</code>```
```<code>            .container{
              min-width: 100px;
              width: min-content;
              height: min-content;
              padding: 10px;
              border: 1px solid black;
            }

            .textbox{
              min-width: 100px;
              width: min-content;
            }
</code>```

答:
I don't think you can check if someone clicked on the empty space of an element.

The best way to do this is to create div as the border of the textbox and check with javascript if the user clicked on the border.

document.getElementById("drag-border").addEventListener("click",function(event){
  //This if blocks calling rest of function when user clicks on textbox and not on border
  if (event.currentTarget !== event.target) {
    return;
  }
  console.log( "Clicked on border" );
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container{
  min-width: 100px;
  width: min-content;
  height: min-content;
}

.textbox{
  min-width: 100px;
  width: min-content;
  border: 1px solid black;
  background: white;
}

#drag-border{
  background: red;
  padding: 10px;
  border: 1px solid black;
}</code>```

```

Body:
I would like to allow editing of text when actual text is clicked. The rest of the white space I need for a dragging functionality.

Is there any way to detect when mouse clicks on text instead of white space in a contenteditable div?

Is there maybe some CSS I can add to a div that would wrap around the text and not the whitespace? Or is there some Javascript that can tell when user clicked on text.

            .container{
              min-width: 100px;
              width: min-content;
              height: min-content;
              padding: 10px;
              border: 1px solid black;
            }

            .textbox{
              min-width: 100px;
              width: min-content;
            }

Body:
I don't think you can check if someone clicked on the empty space of an element.

The best way to do this is to create div as the border of the textbox and check with javascript if the user clicked on the border.

document.getElementById("drag-border").addEventListener("click",function(event){
  //This if blocks calling rest of function when user clicks on textbox and not on border
  if (event.currentTarget !== event.target) {
    return;
  }
  console.log( "Clicked on border" );
});

.container{
  min-width: 100px;
  width: min-content;
  height: min-content;
}

.textbox{
  min-width: 100px;
  width: min-content;
  border: 1px solid black;
  background: white;
}

#drag-border{
  background: red;
  padding: 10px;
  border: 1px solid black;
}

<div class="container">
  <div id="drag-border">
    <div class="textbox" contenteditable="true"></div>
  </div>
</div>


问:
How can i use a const of Vue methods inside a Vue template to show the const result?
I have this alert component and in the body field im trying to use the const "item". The const "item" is in the Vue methods, is it possible to have the const "item" result in that alert body field? I tried {item} {{item}} without success. Thanks</p>
```<code><alert
        v-if="warning"
        :show-alert="showAlert"
        :options="{
          body: "message" {item} {{item}}
        }"
        color="#ffc107"
        style="max-width: 670px; width: 100%;"
        @input="showAlert = false"
      />
...

export default {
  data () {
return {
  warning: '',
  showAlert: true,
  item: null
}

},

...

methods: {
const item = result.hits[0].refs.id[0]

...
</code>```

答:
Is it possible to have the const "item" result in that alert body field?

My Answer is No, Why you want to bind constant in your HTML template ? As you already have item property in your data object. You can update the item value in that property instead of assigning that in const.

For Ex : this.item = 'item value' instead of const item = 'item value'

Body:
I have this alert component and in the body field im trying to use the const "item". The const "item" is in the Vue methods, is it possible to have the const "item" result in that alert body field? I tried {item} {{item}} without success. Thanks

<alert
        v-if="warning"
        :show-alert="showAlert"
        :options="{
          body: "message" {item} {{item}}
        }"
        color="#ffc107"
        style="max-width: 670px; width: 100%;"
        @input="showAlert = false"
      />
...

export default {
  data () {
return {
  warning: '',
  showAlert: true,
  item: null
}

},

...

methods: {
const item = result.hits[0].refs.id[0]

...


问:
$(this).find("a").attr("onclick"); onclick giving invalid character
I m creating a dynamic tab using Jquery its working fine but giving error for anchor tag onclick error is invalid character.
See the javascript:

```<code>$(document).ready(function(){

    //when page loads...
    $(".tab_content").hide(); //hide all content
    $("ol.tabs li:first").addClass("active").show();  //Activate first tab
    $(".tab_content:first").show(); // show first tab content

    //on click event
    $("ol.tabs li").click(function(){
        $("ol.tabs li").removeClass("active"); //remove any "active" class
        $(this).addClass("active"); // add "active" class to selected tabs
        $(".tab_content").hide(); // hide all tab content
        //var activeTab = $(this).find("a").attr("href"); // find href attribute value to identify the active tab + content
        var activeTab = $(this).find("a").attr("onclick"); // find href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); // fadeIn the active ID content
        alert(activeTab);
        return false;
    });

});
</code>```

And the HTML:

```<code><div>
    <div id="tab1" class="tab_content">01</div>
    <div id="tab2" class="tab_content">02</div>
    <div id="tab3" class="tab_content">03</div>
</div>
<ol class="tabs">
    <li><a onclick="#tab1">Unique benefits</a></li>
    <li><a onclick="#tab2">Insurance</a></li>
    <li><a onclick="#tab3">Business Loan</a></li>
</ol>
</code>```

If i use var activeTab = $(this).find("a").attr("href");

Its work fine.
Help out

答:
if you want to get the content(function) of onclick this is how you can go about it:</p>

```<code>$('p').click(function () {
            alert($(this).text());
        });

        $.each($("p").data("events"), function (i, event) {
            alert(i);
            $.each(event, function (j, h) {
                alert(h.handler);
            });
        });
</code>```

Body:
I m creating a dynamic tab using Jquery its working fine but giving error for anchor tag onclick error is invalid character.
See the javascript:

$(document).ready(function(){

    //when page loads...
    $(".tab_content").hide(); //hide all content
    $("ol.tabs li:first").addClass("active").show();  //Activate first tab
    $(".tab_content:first").show(); // show first tab content

    //on click event
    $("ol.tabs li").click(function(){
        $("ol.tabs li").removeClass("active"); //remove any "active" class
        $(this).addClass("active"); // add "active" class to selected tabs
        $(".tab_content").hide(); // hide all tab content
        //var activeTab = $(this).find("a").attr("href"); // find href attribute value to identify the active tab + content
        var activeTab = $(this).find("a").attr("onclick"); // find href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); // fadeIn the active ID content
        alert(activeTab);
        return false;
    });

});

And the HTML:

01

02

03

Unique benefits

Insurance

Business Loan

If i use var activeTab = $(this).find("a").attr("href");

Its work fine.
Help out

Body:
if you want to get the content(function) of onclick this is how you can go about it:

$('p').click(function () {
            alert($(this).text());
        });

        $.each($("p").data("events"), function (i, event) {
            alert(i);
            $.each(event, function (j, h) {
                alert(h.handler);
            });
        });


问:
Cycle inside ; building could produce unreliable results: Xcode Error
I am trying to move to the new build system when compiling with Xcode 10. However, it gives the following error:

```<code>Cycle details:
→ Target 'project' : LinkStoryboards

Target 'project' has compile command with input '/Users/project/Commons/Components/ScreenshotSharing/ViewController/AppShare.storyboard'

Target 'project' : ValidateEmbeddedBinary /Users/project/Xcode/DerivedData/project-hgqvaddkhmzxfkaycbicisabeakv/Build/Products/Debug-iphoneos/project.app/PlugIns/stickers.appex

Target 'project' has process command with input '/Users/project/Resources/Info.plist'

Target 'project' has compile command with input '/Users/project/Commons/Components/ScreenshotSharing/ViewController/AppShare.storyboard'
</code>```

Even after removing the problem file, I get the same for another xib/storyboard. How can I solve this error without reverting to the legacy build system?

答:
In my case,

Removed all pods and reinstall resolved the error

```<code>Remove Pods directory in ios folder
pod install
</code>```

Body:
I am trying to move to the new build system when compiling with Xcode 10. However, it gives the following error:

Cycle details:
→ Target 'project' : LinkStoryboards

Target 'project' has compile command with input '/Users/project/Commons/Components/ScreenshotSharing/ViewController/AppShare.storyboard'

Target 'project' : ValidateEmbeddedBinary /Users/project/Xcode/DerivedData/project-hgqvaddkhmzxfkaycbicisabeakv/Build/Products/Debug-iphoneos/project.app/PlugIns/stickers.appex

Target 'project' has process command with input '/Users/project/Resources/Info.plist'

Target 'project' has compile command with input '/Users/project/Commons/Components/ScreenshotSharing/ViewController/AppShare.storyboard'

Even after removing the problem file, I get the same for another xib/storyboard. How can I solve this error without reverting to the legacy build system?

Body:
In my case,

Removed all pods and reinstall resolved the error

Remove Pods directory in ios folder
pod install


问:
How to remove country code from phone number like example: (855)905649832, +855 98675432 flutter
```<code>RegExp reExp = RegExp(r'^(0|\+|(\+[0-9]{2,4}|\(\+?[0-9]{2,4}\)) ?)([0-9]*|\d{2,4}-\d{2,4}(-\d{2,4})?)$');
String phoneNumber = phoneNumberOne.text.replaceFirst(reExp, '');
</code>```

答:
I think what are you looking for is the following:

You have this input:

```<code>+855 98675432
(855) 98675432
055 98675432
</code>```

and you want to get the output as below:

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

The regex to do that:

void main() {
  RegExp regExp = RegExp(r'^((0[0-9]{2,4}|\+[0-9]{2,4}|\(\+?[0-9]{2,4}\)) ?)');

  String firstNumber = "+855 98675432".replaceFirst(regExp, '');
  print(firstNumber);

  String secondNumber = "(855) 98675432".replaceFirst(regExp, '');
  print(secondNumber);

  String thirdNumber = "055 98675432".replaceFirst(regExp, '');
  print(thirdNumber);
}

```
<p>Explanation:<br />
<code>^</code> means that the string should be at the beginning.<br />
<code>(0[0-9]{2,4}</code> means 0 then two to four numbers in this range 0 to 9.<br />
<code>|</code> means or.<br />
<code>\+[0-9]{2,4}</code> means + then two to four numbers in this range 0 to 9.<br />
<code>\(\+?[0-9]{2,4}\))</code> means + then two to four numbers in this range 0 to 9 in a parentheses.<br />
<code> ?</code> means zero or one space.</p>
<p>The regex above can be even made shorter like this:</p>
```^(\(?(0|\+|)[0-9]{2,4}\)?) ?
```

But it's a little bit harder to read.

Body:
I think what are you looking for is the following:

You have this input:

+855 98675432
(855) 98675432
055 98675432

and you want to get the output as below:

98675432
98675432
98675432

The regex to do that:

void main() {
  RegExp regExp = RegExp(r'^((0[0-9]{2,4}|\+[0-9]{2,4}|\(\+?[0-9]{2,4}\)) ?)');

  String firstNumber = "+855 98675432".replaceFirst(regExp, '');
  print(firstNumber);

  String secondNumber = "(855) 98675432".replaceFirst(regExp, '');
  print(secondNumber);

  String thirdNumber = "055 98675432".replaceFirst(regExp, '');
  print(thirdNumber);
}

Explanation:

^ means that the string should be at the beginning.

(0[0-9]{2,4} means 0 then two to four numbers in this range 0 to 9.

| means or.

\+[0-9]{2,4} means + then two to four numbers in this range 0 to 9.

\(\+?[0-9]{2,4}\)) means + then two to four numbers in this range 0 to 9 in a parentheses.

 ? means zero or one space.

The regex above can be even made shorter like this:

^(\(?(0|\+|)[0-9]{2,4}\)?) ?

But it's a little bit harder to read.


答:
try list for special formate with last one

git tag -l --sort=refname | grep -E '^\d+\.\d+\.\d+.*' | tail -n 1

or first one

git tag -l --sort=refname | grep -E '^\d+\.\d+\.\d+.*' | head -n 1

Title: How to sort git tags by version string order of form rc-X.Y.Z.W?

Body:
When I enter a command:

git tag -l

I get such results:

rc-0.9.0.0
rc-0.9.0.1
rc-0.9.0.10
rc-0.9.0.11
rc-0.9.0.12
rc-0.9.0.2
rc-0.9.0.3
rc-0.9.0.4
rc-0.9.0.5
rc-0.9.0.6
rc-0.9.0.7
rc-0.9.0.8
rc-0.9.0.9

Instead of this I want:

rc-0.9.0.0
rc-0.9.0.1
rc-0.9.0.2
rc-0.9.0.3
rc-0.9.0.4
rc-0.9.0.5
rc-0.9.0.6
rc-0.9.0.7
rc-0.9.0.8
rc-0.9.0.9
rc-0.9.0.10
rc-0.9.0.11
rc-0.9.0.12

How it's possible to sort current list to get such results?


问:
Deduce type from `static constexpr` to `using`
is it possible to "deduce" the type of a static constexpr to a using?

https://compiler-explorer.com/z/hKzqhv7Pa

```<code>#include <chrono>

// Bar.h
using Bar = std::chrono::milliseconds;
static constexpr std::chrono::milliseconds BAR{100};

// Foo.h
struct Foo {
  // Is there a way to get ride of the `using Bar`
  // and "deduce" the type of `BAR` in a  (elegant)
  // way to the `using Type`?
  using Type = Bar // decltype(BAR); // does not compile
  static constexpr auto FOO = BAR;
};

int main() {
  Foo::Type x{0};
  x = Foo::FOO; // candidate function not viable: 'this' argument has type 'Foo::Type' (aka 'const duration<long, ratio<1, 1000> >'), but method is not marked const
  return 0;
}
</code>```

Thanks for the help

Zlatan

答: decltype(BAR) does work. It just returnrs a const type, so the assignment in main fails. Use std::remove_const_t<decltype(BAR)>.

Body:
is it possible to "deduce" the type of a static constexpr to a using?

https://compiler-explorer.com/z/hKzqhv7Pa

#include <chrono>

// Bar.h
using Bar = std::chrono::milliseconds;
static constexpr std::chrono::milliseconds BAR{100};

// Foo.h
struct Foo {
  // Is there a way to get ride of the `using Bar`
  // and "deduce" the type of `BAR` in a  (elegant)
  // way to the `using Type`?
  using Type = Bar // decltype(BAR); // does not compile
  static constexpr auto FOO = BAR;
};

int main() {
  Foo::Type x{0};
  x = Foo::FOO; // candidate function not viable: 'this' argument has type 'Foo::Type' (aka 'const duration<long, ratio<1, 1000> >'), but method is not marked const
  return 0;
}

Thanks for the help

Zlatan


问:
Subtract 1 month of the Calendar Function End Date
I am using a calendar table in an slicer in my Power BI report. In order to avoid the user to select the current month, I would like this calendar to go up to the last day of the previous month. i.e., If we are in February, it would only display the dates until Jan 31.

How can I define the end date of my Calendar DAX.

```<code>    CALENDAR (
              DATE(2019,1,1),
              TODAY()
            )
</code>```

I have tried a couple of things included ENDOFMONTH() and EOMONTH(), but none of them worked.

答:
If you want to exclude, then you could calculate the end date of the previous month using EOMONTH function and then pass this date to CALENDAR, e.g. like this:</p>
```<code>var CalendarTable =
var LastMonthEnd = EOMONTH(TODAY(),-1)
var DatesRange = CALENDAR (
              DATE(2019,1,1),
              LastMonthEnd
            )
return DatesRange
</code>```

Body:
I am using a calendar table in an slicer in my Power BI report. In order to avoid the user to select the current month, I would like this calendar to go up to the last day of the previous month. i.e., If we are in February, it would only display the dates until Jan 31.

How can I define the end date of my Calendar DAX.

    CALENDAR (
              DATE(2019,1,1),
              TODAY()
            )

I have tried a couple of things included ENDOFMONTH() and EOMONTH(), but none of them worked.

Body:
If you want to exclude, then you could calculate the end date of the previous month using EOMONTH function and then pass this date to CALENDAR, e.g. like this:

var CalendarTable =
var LastMonthEnd = EOMONTH(TODAY(),-1)
var DatesRange = CALENDAR (
              DATE(2019,1,1),
              LastMonthEnd
            )
return DatesRange


问:
How to center an image on React
Apologies because this is kind of a simple question, but I have tried a lot of things but still cannot find the solution to center this image: className="meme--image"
I just want that image to be in the center of the page.

Here is my CSS code:

```<code>.form {
    gap: 20px;
    padding-top: 40px;
    padding-left: 50px;
    padding-right: 40px;
    border-radius: 5px;
    display: grid;
    grid-template: 40px 40px  / 1fr 1fr;
}

.form--submit {
    grid-column: 1/ -1;
    background: linear-gradient(90deg, #672280 1.18%, #A626D3 100%);
    color: white;
    border: none;
    cursor: pointer;
    font-family: "Karla", sans-serif;
    border-radius: 5px;
}

.form--input {
    border: 1px solid #D5D4D8;
    border-radius: 0.3125rem;
    font-family: inherit;
    text-indent: 5px;
}
</code>```

Here is my HTML code:

```<code>export default function Input() {
    return (
        <div>
            <div className="form">
                <input type="text" className="form--input" placeholder="Top text" />
                <input type="text" className="form--input" placeholder="Bottom text" />
                <button className="form--submit" onClick={getMemeImage}> Get a new meme image </button>
            </div>
            <img src="https://i.imgflip.com/3lmzyx.jpg"className="meme--image" />
        </div>
    )
}
</code>```

答:
Add a div wrapper for img element with class as image-container and with the following styles.

```
<pre class="lang-css prettyprint-override"><code>.image-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: calc(100vh - 150px);
}
</code>```

Deduction of 150px in height is for the space to the top section.

Title: How to center an image on React

Body:
Apologies because this is kind of a simple question, but I have tried a lot of things but still cannot find the solution to center this image: className="meme--image"
I just want that image to be in the center of the page.

Here is my CSS code:

.form {
    gap: 20px;
    padding-top: 40px;
    padding-left: 50px;
    padding-right: 40px;
    border-radius: 5px;
    display: grid;
    grid-template: 40px 40px  / 1fr 1fr;
}

.form--submit {
    grid-column: 1/ -1;
    background: linear-gradient(90deg, #672280 1.18%, #A626D3 100%);
    color: white;
    border: none;
    cursor: pointer;
    font-family: "Karla", sans-serif;
    border-radius: 5px;
}

.form--input {
    border: 1px solid #D5D4D8;
    border-radius: 0.3125rem;
    font-family: inherit;
    text-indent: 5px;
}

Here is my HTML code:

export default function Input() {
    return (

                <input type="text" className="form--input" placeholder="Top text" />
                <input type="text" className="form--input" placeholder="Bottom text" />
                <button className="form--submit" onClick={getMemeImage}> Get a new meme image </button>

    )
}

Body:
Add a div wrapper for img element with class as image-container and with the following styles.

<div className="image-container">
     <img src="https://i.imgflip.com/3lmzyx.jpg" className="meme--image" />
</div>

.image-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: calc(100vh - 150px);
}

Deduction of 150px in height is for the space to the top section.


答:
According to http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx the offset parameter is an offset inside the byte[] array:

array
      Type: System.Byte[]
      When this method returns, contains the specified byte array with
  the values between offset and (offset + count - 1) replaced by the
  bytes read from the current source.

offset
      Type: System.Int32
      The byte offset in array at which the read bytes will be placed.

count
      Type: System.Int32
      The maximum number of bytes to read.

Read() just reads from the current positon which happens to be a long and should be set before calling Read() see http://msdn.microsoft.com/en-us/library/system.io.filestream.position.aspx

Title: FileStream, read data chunk from big file. Filesize bigger than int. How to set the offset?

Body:
FileStream.Read() is defined as:

public override int Read(
    byte[] array,
    int offset,
    int count
)

How can I read some bytes from an offset bigger than int.MaxValue?

Let's say I have a very big file and I want to read 100MB starting from position 3147483648.

How can I do that?


问:
Xamarin iOS - Disable Back up and Restore for Application
I know Android and iOS can back up app’s data files, the backup data is then allowed to be transferred from old device to new device.

For android, I understand that we can disable backups for your application with <application android:allowBackup="false" ... in AndroidManifest.xml file. I wonder if iOS has the same?

答:
The backup scheme on iOS is more complicated than on android. There is no simple attribute such as android:allowBackup="false" to disable the backup feature globally.

we could use the SetSkipBackupAttribute  function to control whether backup my files.

```<code>NSFileManager.SetSkipBackupAttribute (filename, true); // backup will be skipped for this file
</code>```

Detailed info is here.

Body:
The backup scheme on iOS is more complicated than on android. There is no simple attribute such as android:allowBackup="false" to disable the backup feature globally.

we could use the SetSkipBackupAttribute  function to control whether backup my files.

NSFileManager.SetSkipBackupAttribute (filename, true); // backup will be skipped for this file

Detailed info is here.


问:
How can I console.log an individual attribute from a JSON payload object?
I am trying to console.log some JSON values from an OpeanSea api call payload.
I can successfully hit the end point as seen in the console
when I run this:

```<code>await fetch(`https://api.opensea.io/api/v1/collections?asset_owner=${currentAccount}&offset=0&limit=300`, options)
.then(response => response.json())
.then(response => console.log("collection owned by current address", response))
</code>```

but when I try to log only one attribute from the response object:

```<code>await fetch(`https://api.opensea.io/api/v1/collections?asset_owner=${currentAccount}&offset=0&limit=300`, options)
  .then(response => response.json())
  .then(({ assetts }) => {
    assetts.forEach((attributes) => {
      console.log(attributes.name)
    })
  })
</code>```

I see

```<code>TypeError: Cannot read properties of undefined (reading 'forEach')
</code>```

Is

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

an arbitrary name to iterate through? I think this is what i dont understand

答:
You should know the structure of json and target the required attributes. Like in your case its collections array which is array of object and each object contains name key so you can target key like:

```<code>await fetch(`https://api.opensea.io/api/v1/collections?asset_owner=${currentAccount}&offset=0&limit=300`, options)
    .then((response) => {
      return response.json();
    })
    .then((assetts) => {
      assetts.collections.forEach((attributes) => {
        console.log(attributes.name);
      });
    })
    .catch((error) => {
      console.log({ error });
    });
</code>```

In your first then block you should have to return response after parsing it, if you want to use the parsed data in next then block.

Tip: It is a good practice if you also handle error by putting catch block after then block.

Body:
I am trying to console.log some JSON values from an OpeanSea api call payload.
I can successfully hit the end point as seen in the console
when I run this:

await fetch(`https://api.opensea.io/api/v1/collections?asset_owner=${currentAccount}&offset=0&limit=300`, options)
.then(response => response.json())
.then(response => console.log("collection owned by current address", response))

but when I try to log only one attribute from the response object:

await fetch(`https://api.opensea.io/api/v1/collections?asset_owner=${currentAccount}&offset=0&limit=300`, options)
  .then(response => response.json())
  .then(({ assetts }) => {
    assetts.forEach((attributes) => {
      console.log(attributes.name)
    })
  })

I see

TypeError: Cannot read properties of undefined (reading 'forEach')

Is

assetts

an arbitrary name to iterate through? I think this is what i dont understand

Body:
You should know the structure of json and target the required attributes. Like in your case its collections array which is array of object and each object contains name key so you can target key like:

await fetch(`https://api.opensea.io/api/v1/collections?asset_owner=${currentAccount}&offset=0&limit=300`, options)
    .then((response) => {
      return response.json();
    })
    .then((assetts) => {
      assetts.collections.forEach((attributes) => {
        console.log(attributes.name);
      });
    })
    .catch((error) => {
      console.log({ error });
    });

In your first then block you should have to return response after parsing it, if you want to use the parsed data in next then block.

Tip: It is a good practice if you also handle error by putting catch block after then block.


问:
Apache flink job crashes with exception java.lang.IllegalAccessError: class org.apache.flink.util.NetUtils on start_cluster
Just downloaded Flink 1.13.1 and wanted to run a small local test project. My java version is:

[![enter image description here][1]][1]

```<code>pneelaka@MacBook-Pro Apache %
pneelaka@MacBook-Pro Apache % $FLINK_HOME/bin/start-cluster.sh
Starting cluster.
Starting standalonesession daemon on host MacBook-Pro.
Starting taskexecutor daemon on host MacBook-Pro.
pneelaka@MacBook-Pro Apache %
</code>```

The UI at localhost:8081 does not launch. I see the following in my logs:

```<code>java.lang.IllegalAccessError: class org.apache.flink.util.NetUtils (in unnamed module @0x76e041cf) cannot access class sun.net.util.IPAddressUtil (in module java.base) because module java.base does not export sun.net.util to unnamed module @0x76e041cf
    at org.apache.flink.util.NetUtils.unresolvedHostToNormalizedString(NetUtils.java:169) ~[flink-dist_2.12-1.13.1.jar:1.13.1]
    at org.apache.flink.util.NetUtils.unresolvedHostAndPortToNormalizedString(NetUtils.java:197) ~[flink-dist_2.12-1.13.1.jar:1.13.1]
    at org.apache.flink.runtime.rpc.akka.AkkaRpcServiceUtils.getRpcUrl(AkkaRpcServiceUtils.java:173) ~[flink-dist_2.12-1.13.1.jar:1.13.1]
    at org.apache.flink.runtime.rpc.akka.AkkaRpcServiceUtils.getRpcUrl(AkkaRpcServiceUtils.java:138) ~[flink-dist_2.12-1.13.
</code>```

This heavily seems to be a java version issue ? But wouldn't flink be comptable with latest java? Will I have to go back Java 11 or 8 as it says here: https://ci.apache.org/projects/flink/flink-docs-release-1.13//docs/try-flink/local_installation/#step-1-download

Any suggestions? I have other java versions but my java home points to the latest i.e 16:

```<code>pneelaka@MacBook-Pro Apache % /usr/libexec/java_home -V
Matching Java Virtual Machines (5):
    16.0.1, x86_64: "OpenJDK 16.0.1"    /Users/pneelaka/Library/Java/JavaVirtualMachines/openjdk-16.0.1/Contents/Home
    16.0.1, x86_64: "Java SE 16.0.1"    /Library/Java/JavaVirtualMachines/jdk-16.0.1.jdk/Contents/Home
    14.0.2, x86_64: "OpenJDK 14.0.2"    /Users/pneelaka/Library/Java/JavaVirtualMachines/adopt-openjdk-14.0.2/Contents/Home
    11.0.11.1, x86_64:  "Amazon Corretto 11"    /Users/pneelaka/Library/Java/JavaVirtualMachines/corretto-11.0.11/Contents/Home
    1.8.0_292, x86_64:  "Amazon Corretto 8" /Users/pneelaka/Library/Java/JavaVirtualMachines/corretto-1.8.0_292/Contents/Home
</code>```

UPDATE : Set my java home to point to java 11.0 using

export JAVA_HOME=/usr/libexec/java_home -v 11.0

and it worked

答:
Flink runs on JVM from v1.8 up to v11 but not on the later ones.
The official manual is misleading "Java 1.8.x or higher..."

If you use a package manager (yum, dnf, apt, etc.) then it's enough just make a clean install of java-1.8.0-openjdk and java-1.8.0-openjdk-devel.
You won't need to export any environmental variables. But do not forget to remove any newer/older java versions.

If you have multiple Java versions or if you installed java manually, do:

```<code>export JAVA_HOME=/usr/libexec/java_home -v 1.8.0
</code>```

or whatever your java path is.
You might also need to set paths for JRE_HOME

Body:
Just downloaded Flink 1.13.1 and wanted to run a small local test project. My java version is:

[![enter image description here][1]][1]

pneelaka@MacBook-Pro Apache %
pneelaka@MacBook-Pro Apache % $FLINK_HOME/bin/start-cluster.sh
Starting cluster.
Starting standalonesession daemon on host MacBook-Pro.
Starting taskexecutor daemon on host MacBook-Pro.
pneelaka@MacBook-Pro Apache %

The UI at localhost:8081 does not launch. I see the following in my logs:

java.lang.IllegalAccessError: class org.apache.flink.util.NetUtils (in unnamed module @0x76e041cf) cannot access class sun.net.util.IPAddressUtil (in module java.base) because module java.base does not export sun.net.util to unnamed module @0x76e041cf
    at org.apache.flink.util.NetUtils.unresolvedHostToNormalizedString(NetUtils.java:169) ~[flink-dist_2.12-1.13.1.jar:1.13.1]
    at org.apache.flink.util.NetUtils.unresolvedHostAndPortToNormalizedString(NetUtils.java:197) ~[flink-dist_2.12-1.13.1.jar:1.13.1]
    at org.apache.flink.runtime.rpc.akka.AkkaRpcServiceUtils.getRpcUrl(AkkaRpcServiceUtils.java:173) ~[flink-dist_2.12-1.13.1.jar:1.13.1]
    at org.apache.flink.runtime.rpc.akka.AkkaRpcServiceUtils.getRpcUrl(AkkaRpcServiceUtils.java:138) ~[flink-dist_2.12-1.13.

This heavily seems to be a java version issue ? But wouldn't flink be comptable with latest java? Will I have to go back Java 11 or 8 as it says here: https://ci.apache.org/projects/flink/flink-docs-release-1.13//docs/try-flink/local_installation/#step-1-download

Any suggestions? I have other java versions but my java home points to the latest i.e 16:

pneelaka@MacBook-Pro Apache % /usr/libexec/java_home -V
Matching Java Virtual Machines (5):
    16.0.1, x86_64: "OpenJDK 16.0.1"    /Users/pneelaka/Library/Java/JavaVirtualMachines/openjdk-16.0.1/Contents/Home
    16.0.1, x86_64: "Java SE 16.0.1"    /Library/Java/JavaVirtualMachines/jdk-16.0.1.jdk/Contents/Home
    14.0.2, x86_64: "OpenJDK 14.0.2"    /Users/pneelaka/Library/Java/JavaVirtualMachines/adopt-openjdk-14.0.2/Contents/Home
    11.0.11.1, x86_64:  "Amazon Corretto 11"    /Users/pneelaka/Library/Java/JavaVirtualMachines/corretto-11.0.11/Contents/Home
    1.8.0_292, x86_64:  "Amazon Corretto 8" /Users/pneelaka/Library/Java/JavaVirtualMachines/corretto-1.8.0_292/Contents/Home

UPDATE : Set my java home to point to java 11.0 using

export JAVA_HOME=/usr/libexec/java_home -v 11.0

and it worked

Body:
Flink runs on JVM from v1.8 up to v11 but not on the later ones.
The official manual is misleading "Java 1.8.x or higher..."

If you use a package manager (yum, dnf, apt, etc.) then it's enough just make a clean install of java-1.8.0-openjdk and java-1.8.0-openjdk-devel.
You won't need to export any environmental variables. But do not forget to remove any newer/older java versions.

If you have multiple Java versions or if you installed java manually, do:

export JAVA_HOME=/usr/libexec/java_home -v 1.8.0

or whatever your java path is.
You might also need to set paths for JRE_HOME