问:
how to get current location in google map android
Actually my problem is I am not getting current location latitude and longitude I tried so many ways.I know that this question already asked in SO I tried that answers also still I didn't get answer.Please help me
Code:</p>

```<code>    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
    googleMap.setMyLocationEnabled(true);
    Location myLocation = googleMap.getMyLocation();  //Nullpointer exception.........
    LatLng myLatLng = new LatLng(myLocation.getLatitude(),
            myLocation.getLongitude());

    CameraPosition myPosition = new CameraPosition.Builder()
            .target(myLatLng).zoom(17).bearing(90).tilt(30).build();
    googleMap.animateCamera(
        CameraUpdateFactory.newCameraPosition(myPosition));
</code>```

答:
Select google map activity

you need a Google Maps API key.

To get one, follow this link, follow the directions and press "Create" at the end:
https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=48:C7:A8:5B:31:4F:78:F2:38:41:97:F4:70:C3:A0:EB:6A:73:28:88%3Bcom.example.myapplication

Paste this Code in MapsActivity.java

```<code>import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;

import android.os.Bundle;

import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

  public class MapsActivity extends FragmentActivity implement
   OnMapReadyCallback,
   GoogleApiClient.ConnectionCallbacks,
   GoogleApiClient.OnConnectionFailedListener,
  LocationListener{
</code>```

```<code>    @private GoogleMap mMap;
        GoogleApiClient mGoogleApiClient;
        Location mLastLocation;
        Marker mCurrLocationMarker;
        LocationRequest mLocationRequest;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps);

            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                checkLocationPermission();
            }
            // 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;

            //Initialize Google Play Services
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION) ==
                    PackageManager.PERMISSION_GRANTED) {
                    buildGoogleApiClient();
                    mMap.setMyLocationEnabled(true);
                }
            } else {
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }
        }

        protected synchronized void buildGoogleApiClient() {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
            mGoogleApiClient.connect();
        }

        @Override
        public void onConnected(Bundle bundle) {

            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(1000);
            mLocationRequest.setFastestInterval(1000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) ==
                PackageManager.PERMISSION_GRANTED) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            }

        }

        @Override
        public void onConnectionSuspended(int i) {

        }

        @Override
        public void onLocationChanged(Location location) {

            mLastLocation = location;
            if (mCurrLocationMarker != null) {
                mCurrLocationMarker.remove();
            }

            //Place current location marker
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title("Current Position");
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
            mCurrLocationMarker = mMap.addMarker(markerOptions);

            //move map camera
            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(14));

            //stop location updates
            if (mGoogleApiClient != null) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            }

        }

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {

        }

        public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
        public boolean checkLocationPermission() {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED) {

                // Asking user if explanation is needed
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {

                    // Show an explanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.

                    //Prompt the user once explanation has been shown
                    ActivityCompat.requestPermissions(this,
                        new String[] {
                            Manifest.permission.ACCESS_FINE_LOCATION
                        },
                        MY_PERMISSIONS_REQUEST_LOCATION);

                } else {
                    // No explanation needed, we can request the permission.
                    ActivityCompat.requestPermissions(this,
                        new String[] {
                            Manifest.permission.ACCESS_FINE_LOCATION
                        },
                        MY_PERMISSIONS_REQUEST_LOCATION);
                }
                return false;
            } else {
                return true;
            }
        }

        @Override
        public void onRequestPermissionsResult(int requestCode,
            String permissions[], int[] grantResults) {
            switch (requestCode) {
                case MY_PERMISSIONS_REQUEST_LOCATION:
                    {
                        // If request is cancelled, the result arrays are empty.
                        if (grantResults.length > 0 &&
                            grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                            // permission was granted. Do the
                            // contacts-related task you need to do.
                            if (ContextCompat.checkSelfPermission(this,
                                    Manifest.permission.ACCESS_FINE_LOCATION) ==
                                PackageManager.PERMISSION_GRANTED) {

                                if (mGoogleApiClient == null) {
                                    buildGoogleApiClient();
                                }
                                mMap.setMyLocationEnabled(true);
                            }

                        } else {

                            // Permission denied, Disable the functionality that depends on this permission.
                            Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                        }
                        return;
                    }

            }
        }
    }
</code>```

Make sure these permission are written in Manifest file

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Add following dependencies

implementation 'com.google.android.gms:play-services-maps:17.0.0'

implementation 'com.google.android.gms:play-services-location:17.0.0'

Body:
Actually my problem is I am not getting current location latitude and longitude I tried so many ways.I know that this question already asked in SO I tried that answers also still I didn't get answer.Please help me
Code:

    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
    googleMap.setMyLocationEnabled(true);
    Location myLocation = googleMap.getMyLocation();  //Nullpointer exception.........
    LatLng myLatLng = new LatLng(myLocation.getLatitude(),
            myLocation.getLongitude());

    CameraPosition myPosition = new CameraPosition.Builder()
            .target(myLatLng).zoom(17).bearing(90).tilt(30).build();
    googleMap.animateCamera(
        CameraUpdateFactory.newCameraPosition(myPosition));

Body:
Select google map activity

you need a Google Maps API key.

To get one, follow this link, follow the directions and press "Create" at the end:
https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=48:C7:A8:5B:31:4F:78:F2:38:41:97:F4:70:C3:A0:EB:6A:73:28:88%3Bcom.example.myapplication

Paste this Code in MapsActivity.java

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;

import android.os.Bundle;

import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

  public class MapsActivity extends FragmentActivity implement
   OnMapReadyCallback,
   GoogleApiClient.ConnectionCallbacks,
   GoogleApiClient.OnConnectionFailedListener,
  LocationListener{

    @private GoogleMap mMap;
        GoogleApiClient mGoogleApiClient;
        Location mLastLocation;
        Marker mCurrLocationMarker;
        LocationRequest mLocationRequest;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps);

            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                checkLocationPermission();
            }
            // 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;

            //Initialize Google Play Services
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION) ==
                    PackageManager.PERMISSION_GRANTED) {
                    buildGoogleApiClient();
                    mMap.setMyLocationEnabled(true);
                }
            } else {
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }
        }

        protected synchronized void buildGoogleApiClient() {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
            mGoogleApiClient.connect();
        }

        @Override
        public void onConnected(Bundle bundle) {

            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(1000);
            mLocationRequest.setFastestInterval(1000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) ==
                PackageManager.PERMISSION_GRANTED) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            }

        }

        @Override
        public void onConnectionSuspended(int i) {

        }

        @Override
        public void onLocationChanged(Location location) {

            mLastLocation = location;
            if (mCurrLocationMarker != null) {
                mCurrLocationMarker.remove();
            }

            //Place current location marker
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title("Current Position");
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
            mCurrLocationMarker = mMap.addMarker(markerOptions);

            //move map camera
            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(14));

            //stop location updates
            if (mGoogleApiClient != null) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            }

        }

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {

        }

        public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
        public boolean checkLocationPermission() {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED) {

                // Asking user if explanation is needed
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {

                    // Show an explanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.

                    //Prompt the user once explanation has been shown
                    ActivityCompat.requestPermissions(this,
                        new String[] {
                            Manifest.permission.ACCESS_FINE_LOCATION
                        },
                        MY_PERMISSIONS_REQUEST_LOCATION);

                } else {
                    // No explanation needed, we can request the permission.
                    ActivityCompat.requestPermissions(this,
                        new String[] {
                            Manifest.permission.ACCESS_FINE_LOCATION
                        },
                        MY_PERMISSIONS_REQUEST_LOCATION);
                }
                return false;
            } else {
                return true;
            }
        }

        @Override
        public void onRequestPermissionsResult(int requestCode,
            String permissions[], int[] grantResults) {
            switch (requestCode) {
                case MY_PERMISSIONS_REQUEST_LOCATION:
                    {
                        // If request is cancelled, the result arrays are empty.
                        if (grantResults.length > 0 &&
                            grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                            // permission was granted. Do the
                            // contacts-related task you need to do.
                            if (ContextCompat.checkSelfPermission(this,
                                    Manifest.permission.ACCESS_FINE_LOCATION) ==
                                PackageManager.PERMISSION_GRANTED) {

                                if (mGoogleApiClient == null) {
                                    buildGoogleApiClient();
                                }
                                mMap.setMyLocationEnabled(true);
                            }

                        } else {

                            // Permission denied, Disable the functionality that depends on this permission.
                            Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                        }
                        return;
                    }

            }
        }
    }

Make sure these permission are written in Manifest file

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Add following dependencies

implementation 'com.google.android.gms:play-services-maps:17.0.0'

implementation 'com.google.android.gms:play-services-location:17.0.0'


来源: stackexchange

问:
DotNetOpenAuth POST sample with JSON body
I'm using DotNetOpenAuth and attempting to post a JSON object to a server.

The server is throwing a WebContentType = Raw error.

```<code>Authorization: OAuth
oauth_token="V9vVXD51ehUU6WmY%2FQ41qta0RfY%3D",oauth_consumer_key="CHiawRiAb299cOas",oauth_nonce="BBTM4csg",oauth_signature_method="HMAC-SHA1",oauth_signature="KZJZvT630f2KenB9l9tqSLI%2FfHA%3D",oauth_version="1.0",oauth_timestamp="1306870331"
Content-Type: application/x-www-form-urlencoded; charset=utf-8
User-Agent: DotNetOpenAuth/3.4.6.10357
</code>```

I guess I'm really looking for an example on how to do this? Or a Url to a sample?

I'm currently trying

```<code>WebRequest httpRequest = consumer.
    PrepareAuthorizedRequest(endpoint, AccessToken, para);
httpRequest.ContentType = "application/json";
WebResponse webResponse = httpRequest.GetResponse();
</code>```

答: I believe your mistake is that you're passing in para as a third parameter to PreparedAuthorizedRequest.  If you are passing in extraParameters then you're telling DotNetOpenAuth that these extra parameters must be included in the message payload, which requires a specific content-type.  If you just pass in null as the third parameter I think you can avoid all this header copying and use your own custom content-type.

ContentLicense: CC BY-SA 3.0

Body:
I'm using DotNetOpenAuth and attempting to post a JSON object to a server.

The server is throwing a WebContentType = Raw error.

Authorization: OAuth
oauth_token="V9vVXD51ehUU6WmY%2FQ41qta0RfY%3D",oauth_consumer_key="CHiawRiAb299cOas",oauth_nonce="BBTM4csg",oauth_signature_method="HMAC-SHA1",oauth_signature="KZJZvT630f2KenB9l9tqSLI%2FfHA%3D",oauth_version="1.0",oauth_timestamp="1306870331"
Content-Type: application/x-www-form-urlencoded; charset=utf-8
User-Agent: DotNetOpenAuth/3.4.6.10357

I guess I'm really looking for an example on how to do this? Or a Url to a sample?

I'm currently trying

WebRequest httpRequest = consumer.
    PrepareAuthorizedRequest(endpoint, AccessToken, para);
httpRequest.ContentType = "application/json";
WebResponse webResponse = httpRequest.GetResponse();


问:
WPF Command binding in button inside a materialDesign dialog
Im new to WPF and material desing. And im trying to make a dialog for a confirmation of a button, but when i bind the command and press the button it never gets to the method.

The dialog is made in a dynamicly populated listBox.

Window

```<code>   <ListBox  Height="585"
         Name="NoteList"
         ScrollViewer.CanContentScroll="True"
         ScrollViewer.VerticalScrollBarVisibility="Visible"
         ScrollViewer.HorizontalScrollBarVisibility="Disabled"
         ItemsSource="{Binding dtoRecetas}" Grid.Row="1">

        <ListBox.ItemTemplate>
            <DataTemplate>

               <!--VERSION CARTAS-->
               <materialDesign:Card Style="{StaticResource cardsRecetas}" >
                  <Grid>
                      <Grid.RowDefinitions>
                           <RowDefinition Height="150"/>
                            <RowDefinition Height="170"/>
                       </Grid.RowDefinitions>

                       <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">

                          <!-- DIALOGO DE ELIMINAR RECETA-->
                          <materialDesign:DialogHost  CloseOnClickAway="True" >
                             <materialDesign:DialogHost.DialogContent>
                                 <StackPanel Margin="16">
                                    <TextBlock>Deseas eliminar esta receta</TextBlock>

                                    <StackPanel Orientation="Horizontal"  HorizontalAlignment="Right">

                                       <Button Style="{StaticResource MaterialDesignFlatButton}"
                                                        IsDefault="True"
                                                        Margin="0 8 8 0"
                                                        Command="{Binding Path=comandoDeleteReceta}"
                                                        CommandParameter="{Binding idReceta}">
                                                    Aceptar
                                       </Button>

                                      <Button Style="{StaticResource MaterialDesignFlatButton}"
                                                        Margin="0 8 8 0"
                                                        Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}">
                                              Cancelar
                                       </Button>
                                     </StackPanel>

                                    </StackPanel>
                              </materialDesign:DialogHost.DialogContent>

                             <Button x:Name="btnDeleteReceta" Style="{StaticResource btnDeleteReceta}"
                                        Tag="{Binding idReceta}"
                                        Command="{x:Static materialDesign:DialogHost.OpenDialogCommand}">

                                   <materialDesign:PackIcon Kind="RemoveCircle" />

                                </Button>
                          </materialDesign:DialogHost>

                       </StackPanel>

                    </Grid>
                </materialDesign:Card>

            </DataTemplate>

            </ListBox.ItemTemplate>
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel  ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Disabled"  ></WrapPanel>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
</code>```

ViewModel

```<code> public class VerRecetasViewModel : BaseViewModel
    {
        public Command comandoDeleteReceta { get; set; }
        public ObservableCollection<DTOReceta> dtoRecetas { get; set; }

        public VerRecetasViewModel()
        {
            RecetasController recController = new RecetasController();
            dtoRecetas = new ObservableCollection<DTOReceta>(recController.getAllRecetas());

            comandoDeleteReceta = new Command();
            comandoDeleteReceta.CanExecuteFunc = obj => true;
            comandoDeleteReceta.ExecuteFunc = deleteReceta;
        }

        public void deleteReceta(object parameter)
        {
            int idReceta = (int)parameter;
            RecetasController recController = new RecetasController();
            recController.deleteReceta(idReceta);
        }

    }
</code>```

The desired behavior is that when they press "Aceptar" it gets to the "deleteReceta" method, but as right now it looks like is not finding the binded command.

The command class is working and i use commands in other windows this way and it works, i think im losing the context from the dialog or creating it wrong. I tried this way and adding relative source to the binding, but i dont know what the ancestortype should be.

Thanks for the help.

答:
I think it's a problem with the DataContext. So I would set the dataContext of the view like this :
d:DataContext="{d:DesignInstance {x:Type vm:VerRecetasViewModel}}"

and in the ListBox, bind the command on the button like this :

```<code>Command="{Binding DataContext.comandoDeleteReceta, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}"
</code>```

Hope this helps

ContentLicense: CC BY-SA 4.0

Body:
Im new to WPF and material desing. And im trying to make a dialog for a confirmation of a button, but when i bind the command and press the button it never gets to the method.

The dialog is made in a dynamicly populated listBox.

Window

   <ListBox  Height="585"
         Name="NoteList"
         ScrollViewer.CanContentScroll="True"
         ScrollViewer.VerticalScrollBarVisibility="Visible"
         ScrollViewer.HorizontalScrollBarVisibility="Disabled"
         ItemsSource="{Binding dtoRecetas}" Grid.Row="1">

        <ListBox.ItemTemplate>
            <DataTemplate>

               <materialDesign:Card Style="{StaticResource cardsRecetas}" >
                  <Grid>
                      <Grid.RowDefinitions>
                           <RowDefinition Height="150"/>
                            <RowDefinition Height="170"/>
                       </Grid.RowDefinitions>

                       <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">

                          <materialDesign:DialogHost  CloseOnClickAway="True" >
                             <materialDesign:DialogHost.DialogContent>
                                 <StackPanel Margin="16">
                                    <TextBlock>Deseas eliminar esta receta</TextBlock>

                                    <StackPanel Orientation="Horizontal"  HorizontalAlignment="Right">

                                       <Button Style="{StaticResource MaterialDesignFlatButton}"
                                                        IsDefault="True"
                                                        Margin="0 8 8 0"
                                                        Command="{Binding Path=comandoDeleteReceta}"
                                                        CommandParameter="{Binding idReceta}">
                                                    Aceptar
                                       </Button>

                                      <Button Style="{StaticResource MaterialDesignFlatButton}"
                                                        Margin="0 8 8 0"
                                                        Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}">
                                              Cancelar
                                       </Button>
                                     </StackPanel>

                                    </StackPanel>
                              </materialDesign:DialogHost.DialogContent>

                             <Button x:Name="btnDeleteReceta" Style="{StaticResource btnDeleteReceta}"
                                        Tag="{Binding idReceta}"
                                        Command="{x:Static materialDesign:DialogHost.OpenDialogCommand}">

                                   <materialDesign:PackIcon Kind="RemoveCircle" />

                                </Button>
                          </materialDesign:DialogHost>

                       </StackPanel>

                    </Grid>
                </materialDesign:Card>

            </DataTemplate>

            </ListBox.ItemTemplate>
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel  ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Disabled"  ></WrapPanel>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>

ViewModel

 public class VerRecetasViewModel : BaseViewModel
    {
        public Command comandoDeleteReceta { get; set; }
        public ObservableCollection<DTOReceta> dtoRecetas { get; set; }

        public VerRecetasViewModel()
        {
            RecetasController recController = new RecetasController();
            dtoRecetas = new ObservableCollection<DTOReceta>(recController.getAllRecetas());

            comandoDeleteReceta = new Command();
            comandoDeleteReceta.CanExecuteFunc = obj => true;
            comandoDeleteReceta.ExecuteFunc = deleteReceta;
        }

        public void deleteReceta(object parameter)
        {
            int idReceta = (int)parameter;
            RecetasController recController = new RecetasController();
            recController.deleteReceta(idReceta);
        }

    }

The desired behavior is that when they press "Aceptar" it gets to the "deleteReceta" method, but as right now it looks like is not finding the binded command.

The command class is working and i use commands in other windows this way and it works, i think im losing the context from the dialog or creating it wrong. I tried this way and adding relative source to the binding, but i dont know what the ancestortype should be.

Thanks for the help.

Body:
I think it's a problem with the DataContext. So I would set the dataContext of the view like this :
d:DataContext="{d:DesignInstance {x:Type vm:VerRecetasViewModel}}"

and in the ListBox, bind the command on the button like this :

Command="{Binding DataContext.comandoDeleteReceta, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}"

Hope this helps


问:
Bokeh get selected glyphs/annotations from TapTool
For my project I need to add and remove glpyhs and annotations in bokeh (line, multiline and arrows).  I want to make it as interactive as possible. So in order to remove a glyph/annotation in want to select it with a mouse click and then e.g. delete it with a button. The minimal example would look like that:

import numpy as np
import random
from bokeh.plotting import figure, ColumnDataSource
from bokeh.models import Button, TapTool,Arrow,NormalHead
from bokeh.layouts import layout

from bokeh.application import Application
from bokeh.server.server import Server
from bokeh.application.handlers.function import FunctionHandler

plot = figure(plot_height=300, plot_width=600, x_range=(0, 8), y_range=(0, 11),
                   title="Testplot", tools='save, reset, tap')

Lay = layout(children=[])

#adds the glyphs/annotaions to figure
def Click_action():
    x = np.array((random.randrange(1,10),random.randrange(1,10)))
    y = np.array((random.randrange(1,10),random.randrange(1,10)))

    source = ColumnDataSource(data=dict(x = x,
                                        y = y))

    arro = Arrow(end=NormalHead(size=5, fill_color="#C0392B"),
                 x_start=random.randrange(0,10),
                 y_start=random.randrange(0,10),
                 x_end=random.randrange(0,10),
                 y_end=random.randrange(0,10),
                 line_width=3,
                 line_color="#C0392B")

    plot.multi_line(xs=[[1,5],[1,1],[3,3],[5,5]],ys=[[5,5],[5,1],[5,1],[5,1]], color='blue', selection_color='red' )
    plot.add_layout(arro)
    plot.line(x='x',y='y', source = source,selection_color='red')
def Click_delet():
    """ Delete the selected Glyphs/Annotations"""
def make_document(doc):

    btn1 = Button(label="Click", button_type="success")

    btn2 = Button(label="Click_delet", button_type="success")
    btn1.on_click(Click_action)
    btn2.on_click(Click_delet)
    Lay.children.append(plot)
    Lay.children.append(btn1)
    Lay.children.append(btn2)
    doc.add_root(Lay)

if __name__ == '__main__':
    bkapp = {'/': Application(FunctionHandler(make_document))}
    server = Server(bkapp, port=5004)
    server.start()
    server.io_loop.add_callback(server.show, "/")
    server.io_loop.start()

```

The problems I currently have are:

How can I select the arrow ?

How do I get all selected glyphs and annotations? (If possible without a CoustomJS callback since  I do not know java that well)

Is it possible to select the multiline as one glyph?

I have already solved the issue how to delete lines and arrows from a plot. But I would need the value stored in plot.renders and plot.center in order to delete them and link them to different classes in my project.

答:
Annotations are not interactive in Bokeh

See a minimal example below

No

But I would need the value stored in plot.renders and plot.center in order to delete them and link them to different classes in my project.

Ideally, your workflow should abstain from dynamically creating and removing Bokeh models, especially low-levels ones such as glyphs. If you need to remove a glyph and add a new one with new properties, consider just changing properties of the old glyph. Or maybe just clear the data of the old glyph to hide it.

from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models import Button
from bokeh.plotting import figure, ColumnDataSource

line_ds = ColumnDataSource(dict(x=[0, 3, 7],
                                y=[1, 8, 2]))
multi_line_ds = ColumnDataSource(dict(xs=[[1, 5], [1, 1], [3, 3], [5, 5]],
                                      ys=[[5, 5], [5, 1], [5, 1], [5, 1]]))

p = figure(x_range=(0, 8), y_range=(0, 11), tools='save, reset, tap')

p.line('x', 'y', source=line_ds, selection_color='red')
p.multi_line('xs', 'ys', source=multi_line_ds, color='blue', selection_color='red')

b = Button(label="Delete selected", button_type="success")

def delete_rows(ds, indices):
    print(indices)
    if indices:
        print(ds.data)
        ds.data = {k: [v for i, v in enumerate(vs) if i not in set(indices)]
                   for k, vs in ds.data.items()}
        print(ds.data)

def delete_selected():
    delete_rows(line_ds, line_ds.selected.line_indices)
    delete_rows(multi_line_ds, multi_line_ds.selected.indices)

b.on_click(delete_selected)

curdoc().add_root(column(p, b))
```

Body:
For my project I need to add and remove glpyhs and annotations in bokeh (line, multiline and arrows).  I want to make it as interactive as possible. So in order to remove a glyph/annotation in want to select it with a mouse click and then e.g. delete it with a button. The minimal example would look like that:

import numpy as np
import random
from bokeh.plotting import figure, ColumnDataSource
from bokeh.models import Button, TapTool,Arrow,NormalHead
from bokeh.layouts import layout

from bokeh.application import Application
from bokeh.server.server import Server
from bokeh.application.handlers.function import FunctionHandler

plot = figure(plot_height=300, plot_width=600, x_range=(0, 8), y_range=(0, 11),
                   title="Testplot", tools='save, reset, tap')

Lay = layout(children=[])

#adds the glyphs/annotaions to figure
def Click_action():
    x = np.array((random.randrange(1,10),random.randrange(1,10)))
    y = np.array((random.randrange(1,10),random.randrange(1,10)))

    source = ColumnDataSource(data=dict(x = x,
                                        y = y))

    arro = Arrow(end=NormalHead(size=5, fill_color="#C0392B"),
                 x_start=random.randrange(0,10),
                 y_start=random.randrange(0,10),
                 x_end=random.randrange(0,10),
                 y_end=random.randrange(0,10),
                 line_width=3,
                 line_color="#C0392B")

    plot.multi_line(xs=[[1,5],[1,1],[3,3],[5,5]],ys=[[5,5],[5,1],[5,1],[5,1]], color='blue', selection_color='red' )
    plot.add_layout(arro)
    plot.line(x='x',y='y', source = source,selection_color='red')
def Click_delet():
    """ Delete the selected Glyphs/Annotations"""
def make_document(doc):

    btn1 = Button(label="Click", button_type="success")

    btn2 = Button(label="Click_delet", button_type="success")
    btn1.on_click(Click_action)
    btn2.on_click(Click_delet)
    Lay.children.append(plot)
    Lay.children.append(btn1)
    Lay.children.append(btn2)
    doc.add_root(Lay)

if __name__ == '__main__':
    bkapp = {'/': Application(FunctionHandler(make_document))}
    server = Server(bkapp, port=5004)
    server.start()
    server.io_loop.add_callback(server.show, "/")
    server.io_loop.start()

The problems I currently have are:

How can I select the arrow ?

How do I get all selected glyphs and annotations? (If possible without a CoustomJS callback since  I do not know java that well)

Is it possible to select the multiline as one glyph?

I have already solved the issue how to delete lines and arrows from a plot. But I would need the value stored in plot.renders and plot.center in order to delete them and link them to different classes in my project.


问:
Python: Get data after second underscore from back?
I'm trying to get data after second underscore from back?

sample:

str

```<code>a_bc_def 12_23_this_6729

abc_def,122$3_this_6729

abc_def_1_2_23_this_6729
</code>```

output

```<code>this_6729
</code>```

答:
You can try rfind twice like

```<code>a = "a_bc_def 12_23_this_6729"
a[a[:a.rfind("_")].rfind("_") + 1:]
</code>```

Output

```<code>'this_6729'
</code>```

Body:
I'm trying to get data after second underscore from back?

sample:

str

a_bc_def 12_23_this_6729

abc_def,122$3_this_6729

abc_def_1_2_23_this_6729

output

this_6729

Body:
You can try rfind twice like

a = "a_bc_def 12_23_this_6729"
a[a[:a.rfind("_")].rfind("_") + 1:]

Output

'this_6729'


问:
Django: use of __lte for automatic publication of a post
I'm developing a blog and I'm using this filter for put online the posts automatically:

```<code>geopost_filter = GeoPost.objects.filter(draft=False, publishing_date__lte=timezone.now())
</code>```

This filter run in local but doesn't run in production. For put online the post that pass from "it will be published in future" to "it is now online" I must restart the server in production.

Why happen this?

I can change the post's status using the draft field without problem, both in local than in production. But it seams not possible to publish automatically a post if it is marked as future post.

EDIT after request from Willem Van Onsem

I use this filter into a view and into an api view.

```<code>from django.core.paginator import Paginator
from django.db.models.functions import Now
from django.shortcuts import get_object_or_404, redirect, render
from .models import GeoPost, GeoTag

geopost_filter = GeoPost.objects.filter(
    draft=False,
    publishing_date__lte=Now()
)

def geotag_single(request, slug_tag):
    geotag = get_object_or_404(GeoTag, slug_tag=slug_tag)
    geopost_full = geopost_filter.filter(tags=geotag)

    paginator = Paginator(geopost_full, 10)
    page = request.GET.get("pagina")
    geopost_list = paginator.get_page(page)

    context = {
            "tag": geotag,
            "post_list": geopost_list,
            }

    return render(request, 'geoblog/single_tag.html', context)
</code>```

apiviews

```<code>from rest_framework.decorators import api_view
from rest_framework.response import Response
from geoblog.models import GeoPost
from geoblog.views import geopost_filter

@api_view(["GET"])
def geoblogPost_apiview(request):
    if request.method == "GET":
        if request.user.is_staff:
            objects = GeoPost.objects.all()
        else:
            objects = geopost_filter
        serializer = GeoPostSerializer(objects, many=True)
        return Response(serializer.data)
</code>```

GeoPost is a model that use the PontField together the classical fields of a blog post like title and contents. This is an example:

```<code>from django.contrib.gis.db import models
from django.utils import timezone

GeoPost(models.Model):
    geom = models.PointField(
        blank=True,
        null=True,
    )
    publishing_date = models.DateTimeField(
        default=timezone.now,
        )
    title = models.CharField(
        max_length=70,
        unique=True,
    )
    contents = models.TextField()
    draft = models.BooleanField()
</code>```

Maybe the problem is in publishing_date because I use timezone.now?

答:
Likely you defined the query once, and reuse it multiple times. As a result the timezone.now is not updated, and thus the "new" GeoPosts do not get published.

You can however make use of the database time with a Now expression [Django-doc]:

```<code>from django.db.models.functions import <b>Now</b>

geopost_filter = GeoPost.objects.filter(
    draft=False, publishing_date__lte=<b>Now()</b>
)</code>```

Here Now is not converted to the time when you construct the queryset, it uses the time at the database, so you can reuse this queryset.

Another problem is that you make use of a global variable, and thus the results get cached. This means that after making one query, the query is not done again. You can force requerying, for example with .all():

```<code>@api_view(["GET"])
def geoblogPost_apiview(request):
    if request.method == "GET":
        if request.user.is_staff:
            objects = GeoPost.objects.all()
        else:
            objects = <b>geopost_filter.all()</b>
        serializer = GeoPostSerializer(objects, many=True)
        return Response(serializer.data)</code>```

Body:
I'm developing a blog and I'm using this filter for put online the posts automatically:

geopost_filter = GeoPost.objects.filter(draft=False, publishing_date__lte=timezone.now())

This filter run in local but doesn't run in production. For put online the post that pass from "it will be published in future" to "it is now online" I must restart the server in production.

Why happen this?

I can change the post's status using the draft field without problem, both in local than in production. But it seams not possible to publish automatically a post if it is marked as future post.

EDIT after request from Willem Van Onsem

I use this filter into a view and into an api view.

from django.core.paginator import Paginator
from django.db.models.functions import Now
from django.shortcuts import get_object_or_404, redirect, render
from .models import GeoPost, GeoTag

geopost_filter = GeoPost.objects.filter(
    draft=False,
    publishing_date__lte=Now()
)

def geotag_single(request, slug_tag):
    geotag = get_object_or_404(GeoTag, slug_tag=slug_tag)
    geopost_full = geopost_filter.filter(tags=geotag)

    paginator = Paginator(geopost_full, 10)
    page = request.GET.get("pagina")
    geopost_list = paginator.get_page(page)

    context = {
            "tag": geotag,
            "post_list": geopost_list,
            }

    return render(request, 'geoblog/single_tag.html', context)

apiviews

from rest_framework.decorators import api_view
from rest_framework.response import Response
from geoblog.models import GeoPost
from geoblog.views import geopost_filter

@api_view(["GET"])
def geoblogPost_apiview(request):
    if request.method == "GET":
        if request.user.is_staff:
            objects = GeoPost.objects.all()
        else:
            objects = geopost_filter
        serializer = GeoPostSerializer(objects, many=True)
        return Response(serializer.data)

GeoPost is a model that use the PontField together the classical fields of a blog post like title and contents. This is an example:

from django.contrib.gis.db import models
from django.utils import timezone

GeoPost(models.Model):
    geom = models.PointField(
        blank=True,
        null=True,
    )
    publishing_date = models.DateTimeField(
        default=timezone.now,
        )
    title = models.CharField(
        max_length=70,
        unique=True,
    )
    contents = models.TextField()
    draft = models.BooleanField()

Maybe the problem is in publishing_date because I use timezone.now?

Body:
Likely you defined the query once, and reuse it multiple times. As a result the timezone.now is not updated, and thus the "new" GeoPosts do not get published.

You can however make use of the database time with a Now expression [Django-doc]:

from django.db.models.functions import Now

geopost_filter = GeoPost.objects.filter(
    draft=False, publishing_date__lte=Now()
)

Here Now is not converted to the time when you construct the queryset, it uses the time at the database, so you can reuse this queryset.

Another problem is that you make use of a global variable, and thus the results get cached. This means that after making one query, the query is not done again. You can force requerying, for example with .all():

@api_view(["GET"])
def geoblogPost_apiview(request):
    if request.method == "GET":
        if request.user.is_staff:
            objects = GeoPost.objects.all()
        else:
            objects = geopost_filter.all()
        serializer = GeoPostSerializer(objects, many=True)
        return Response(serializer.data)


问:
Sorting v-data-table checks checkboxes
Is anyone able to determine why sorting this table will automatically check some boxes? And how the boxes can be checked when their value is not in the "checked" array?

    <v-app id="inspire">

            <v-data-table
                show-select
                :headers="headers"
                :items="desserts"
                class="elevation-1"
            >
                <template v-slot:items="props">
                    <v-checkbox v-model="checked" :value="props.item.name" />
                    {{ props.item.name }}
                    {{ props.item.calories }}
                </template>
            </v-data-table>

    </v-app>

```

CodePen: https://codepen.io/EoghanCurtin/pen/ExPYqpY

答:
UPDATE

If you want your checkboxes to follow their corresponding item when sorting - then you will have to change their definition like this

```<code><v-checkbox
  :value="checked.includes(props.item.name)"
  @change="toggleCheckbox(props.item.name)"
/>
</code>```

and then use the following function to toggle the on/off state

    toggleCheckbox(item)
    {
      const idx = this.checked.indexOf(item);
      if(idx === -1) this.checked.push(item);
      else this.checked.splice(idx,1);
    }
```

When the data-table sorts its items - it does not sort your checkboxes. So your checkboxes' value is being changed dynamically (because corresponding item.name is different after sorting).

If you need no more than 1 checkbox per row - it is better to utilize the built-in checking support for data-tables

Title: Sorting v-data-table checks checkboxes

Body:
Is anyone able to determine why sorting this table will automatically check some boxes? And how the boxes can be checked when their value is not in the "checked" array?

    <v-app id="inspire">

            <v-data-table
                show-select
                :headers="headers"
                :items="desserts"
                class="elevation-1"
            >
                <template v-slot:items="props">
                    <v-checkbox v-model="checked" :value="props.item.name" />
                    {{ props.item.name }}
                    {{ props.item.calories }}
                </template>
            </v-data-table>

    </v-app>

CodePen: https://codepen.io/EoghanCurtin/pen/ExPYqpY

Body:
UPDATE

If you want your checkboxes to follow their corresponding item when sorting - then you will have to change their definition like this

<v-checkbox
  :value="checked.includes(props.item.name)"
  @change="toggleCheckbox(props.item.name)"
/>

and then use the following function to toggle the on/off state

    toggleCheckbox(item)
    {
      const idx = this.checked.indexOf(item);
      if(idx === -1) this.checked.push(item);
      else this.checked.splice(idx,1);
    }

When the data-table sorts its items - it does not sort your checkboxes. So your checkboxes' value is being changed dynamically (because corresponding item.name is different after sorting).

If you need no more than 1 checkbox per row - it is better to utilize the built-in checking support for data-tables


问:
objective c memory leak with array?
In my application i declare an array property,

```<code>@property (nonatomic, retain) NSArray *listOfItems;
</code>```

and in my viewDidLoad method,

```<code>listOfItems = [[NSArray alloc] initWithObjects:@"First", @"Second", nil];
</code>```

I do not release the array in my viewDidLoad, because the objects in the array will be required elsewhere in the application.

Finally in my dealloc method i put,

```<code>[listOfItems release];
</code>```

My question is: Is there a memory leak in this code? The retain count should be increased twice due to the (retain) in the property as well as the alloc in the viewDidLoad, but only decreased once in the dealloc method.

答:
It wont be confusing if you practice like this  </p>

```<code>@property (nonatomic, retain) NSArray *listOfItems;
NSArray *temparray = [[NSArray alloc] initWithObjects:@"First", @"Second", nil];
self.listOfItems = temparray;
[temparray release];
</code>```

<p>and in dealloc  </p>

```<code>[listOfItems release];
</code>```

Title: objective c memory leak with array?

Body:
In my application i declare an array property,

@property (nonatomic, retain) NSArray *listOfItems;

and in my viewDidLoad method,

listOfItems = [[NSArray alloc] initWithObjects:@"First", @"Second", nil];

I do not release the array in my viewDidLoad, because the objects in the array will be required elsewhere in the application.

Finally in my dealloc method i put,

[listOfItems release];

My question is: Is there a memory leak in this code? The retain count should be increased twice due to the (retain) in the property as well as the alloc in the viewDidLoad, but only decreased once in the dealloc method.

Body:
It wont be confusing if you practice like this

@property (nonatomic, retain) NSArray *listOfItems;
NSArray *temparray = [[NSArray alloc] initWithObjects:@"First", @"Second", nil];
self.listOfItems = temparray;
[temparray release];

and in dealloc

[listOfItems release];


问:
How to break a dynamic(changing) string into two different parts?
I had a field from the API response which gives me data like "Welcome Name" or it can be "Welcome back Name". Name can be any combination of firstName middleName lastName. I want to break it into two parts,

1 - "Welcome" or "Welcome back" (as per the response from API)

2 - "Name"

```<code>for example :

if data is "Welcome Aman Pratap Singh" break into 1-"Welcome" 2-"Aman Pratap Singh"

if data is "Welcome back ABCDE PQR XYZ" break into 1-"Welcome back" 2-"ABCDE PQR XYZ"

if data is "Welcome ABC XYZ" break into 1-"Welcome" 2-"ABC XYZ"

if data is "Welcome back ABC XYZ" break into 1-"Welcome back" 2-"ABC XYZ"

if data is  "Welcome ABCDE" break into 1-"Welcome" 2-"ABCDE"

if data is  "Welcome back ABCDE" break into 1-"Welcome back" 2-"ABCDE"
</code>```

答:
A simple regex ought to be able to do this:

let splitWelcomeStr = str => {
  let match = str.match(/^(Welcome( back)?) (.+)$/);
  if (!match) throw new Error('Invalid welcome string provided');
  return { welcome: match[1], name: match[3] };
};

console.log(splitWelcomeStr('Welcome John'));
console.log(splitWelcomeStr('Welcome John Doe'));
console.log(splitWelcomeStr('Welcome John H. Doe'));
console.log(splitWelcomeStr('Welcome back John'));
console.log(splitWelcomeStr('Welcome back John Doe'));
console.log(splitWelcomeStr('Welcome back John H. Doe'));
console.log(splitWelcomeStr('Welcome back'));
console.log(splitWelcomeStr('Welcome back back'));```
</div>
</div>
</p>

<p>A breakdown of the regex used:</p>

```^(Welcome( back)?) (.+)$

^                         Match the start of the sequence
 (               )        Create a result at index 1
  Welcome                 The string "Welcome"
         (     )?         An optional string (and a result at index 2)
           back           The string " back" (prefixed with a space!)
                   (.+)   A space followed by  match at index 3 for any further characters
                       $  Match the end of the sequence
```

Body:
I had a field from the API response which gives me data like "Welcome Name" or it can be "Welcome back Name". Name can be any combination of firstName middleName lastName. I want to break it into two parts,

1 - "Welcome" or "Welcome back" (as per the response from API)

2 - "Name"

for example :

if data is "Welcome Aman Pratap Singh" break into 1-"Welcome" 2-"Aman Pratap Singh"

if data is "Welcome back ABCDE PQR XYZ" break into 1-"Welcome back" 2-"ABCDE PQR XYZ"

if data is "Welcome ABC XYZ" break into 1-"Welcome" 2-"ABC XYZ"

if data is "Welcome back ABC XYZ" break into 1-"Welcome back" 2-"ABC XYZ"

if data is  "Welcome ABCDE" break into 1-"Welcome" 2-"ABCDE"

if data is  "Welcome back ABCDE" break into 1-"Welcome back" 2-"ABCDE"

Body:
A simple regex ought to be able to do this:

let splitWelcomeStr = str => {
  let match = str.match(/^(Welcome( back)?) (.+)$/);
  if (!match) throw new Error('Invalid welcome string provided');
  return { welcome: match[1], name: match[3] };
};

console.log(splitWelcomeStr('Welcome John'));
console.log(splitWelcomeStr('Welcome John Doe'));
console.log(splitWelcomeStr('Welcome John H. Doe'));
console.log(splitWelcomeStr('Welcome back John'));
console.log(splitWelcomeStr('Welcome back John Doe'));
console.log(splitWelcomeStr('Welcome back John H. Doe'));
console.log(splitWelcomeStr('Welcome back'));
console.log(splitWelcomeStr('Welcome back back'));

A breakdown of the regex used:

^(Welcome( back)?) (.+)$

^                         Match the start of the sequence
 (               )        Create a result at index 1
  Welcome                 The string "Welcome"
         (     )?         An optional string (and a result at index 2)
           back           The string " back" (prefixed with a space!)
                   (.+)   A space followed by  match at index 3 for any further characters
                       $  Match the end of the sequence


问:
How can I know both class are from same Generic class
Here is sample code. How can I know both Foo and Bar are from same class Base<>?

```<code>class Program
{
    static void Main(string[] args)
    {
        var foo = typeof(Foo).IsAssignableFrom(typeof(Base<,>));
        var bar = typeof(Bar).IsAssignableFrom(typeof(Base<,>));
    }
}

public abstract class Base<TInput, TOutput>
{
    public abstract TOutput Run(TInput input);
}

public class Foo : Base<int, string>
{
    public override string Run(int input)
    {
        return input.ToString();
    }
}

public class Bar : Base<string, string>
{
    public override string Run(string input)
    {
        return input.Replace(".", "").ToString();
    }
}
</code>```

答:
To make your code compile you will need to change Base<> to Base<,> because it has two type parameters. Still IsAssignableFrom should not work cause, maybe something like this will work for you:

```<code>var foo = typeof(Foo).BaseType.GetGenericTypeDefinition() == (typeof(Base<,>));
var bar = typeof(Bar).BaseType.GetGenericTypeDefinition() == (typeof(Base<,>));
</code>```

?

Body:
Here is sample code. How can I know both Foo and Bar are from same class Base<>?

class Program
{
    static void Main(string[] args)
    {
        var foo = typeof(Foo).IsAssignableFrom(typeof(Base<,>));
        var bar = typeof(Bar).IsAssignableFrom(typeof(Base<,>));
    }
}

public abstract class Base<TInput, TOutput>
{
    public abstract TOutput Run(TInput input);
}

public class Foo : Base<int, string>
{
    public override string Run(int input)
    {
        return input.ToString();
    }
}

public class Bar : Base<string, string>
{
    public override string Run(string input)
    {
        return input.Replace(".", "").ToString();
    }
}

Body:
To make your code compile you will need to change Base<> to Base<,> because it has two type parameters. Still IsAssignableFrom should not work cause, maybe something like this will work for you:

var foo = typeof(Foo).BaseType.GetGenericTypeDefinition() == (typeof(Base<,>));
var bar = typeof(Bar).BaseType.GetGenericTypeDefinition() == (typeof(Base<,>));

?


问:
I need advise to decide on the Software Architecture for a WebApp
I am in the phase of planning for a scalable and huge web application, I've decided to implement Microservices and Multi-Tenants with DB per tenant. After doing some research I was tending to select ASP.NET Core as my development framework, but then someone advised me to separate the development entities having the back-end, APIs and front-end separately, but then I will lose the debugging and pre-compile advantages of ASP.NET. Also, If I'm willing to use serverless functions I was advised not to go with ASP.NET for some limitations. So I'm thinking between PHP or Python or NodeJs!

I've been developing using the traditional methods since long time and I'm confused with all these new and interesting concepts. I will build a team to do the development but I need to decide on the architecture design and which languages to use and on what environments (tending to host on AWS). I need more clarification regarding how to separate the entities and what are the best practices.

Can you please help me with this?

Appreciated!

答:
The language here is not mandatory, but I would split the services, Web, Backend and API, it is a better architecture than shipping everything together.

PHP is quite famous, but I never used, I use python and like it a lot, nodeJS is quite popular and has a huge set of frameworks. In a micro services world you can use any language. Each microservice is independent.

I am a AWS user and it a great cloud provider.

Take a read on serverless architecting on AWS. It will give a good idea on the field.  here the link:
https://d1.awsstatic.com/whitepapers/serverless-architectures-with-aws-lambda.pdf

Here a great website on microservices:
https://martinfowler.com/microservices/

Best Regards,


问:
Loop in an update SQL Server query sent by MS Access vba
I am using MS Access vba as the interface and SQL Server as database server.

I want to update a set of rows in a table CANDIDAT_TESTS. What I am now doing is update one by one and I loop with a for loop; it works, but it takes too much time.

I would like to reduce the number of query by looping in one query.

My code:

```<code>This is the entire code
</code>```

´´´ varSession = "2020"
    Set cnx = getConnectionBD(varSession)

```<code>rsSCE.Open "SELECT DISTINCT LIBELLE_DEPARTEMENT, LIBELLE_SOUS_CENTRE, NUM_SOUS_CENTRE " _
    & " FROM VIEW_CANDIDATS_SCE " _
    & " WHERE NUM_REGION = " & Me.LIST_REGION & " AND NUM_EXAMEN = " & Me.LIST_EXAMEN _
    & " ORDER BY LIBELLE_DEPARTEMENT, LIBELLE_SOUS_CENTRE", cnx, adOpenStatic, adLockOptimistic
varTabSCE = rsSCE.GetRows
'On initialise les jurys parce que les jurys sont par région
jury = 0

'On parcourt les sous-centres par départements
For j = 1 To rsSCE.RecordCount
    rsSerie.Open "SELECT DISTINCT NUM_SERIE, ABREVIATION_SERIE " _
        & " FROM VIEW_CANDIDATS_SCE " _
        & " WHERE NUM_SOUS_CENTRE = " & varTabSCE(2, j - 1) & " AND NUM_EXAMEN = " & Me.LIST_EXAMEN _
        & " ORDER BY ABREVIATION_SERIE", cnx, adOpenStatic, adLockOptimistic
    varTabSerie = rsSerie.GetRows

    'On parcourt les séries du sce j
    For k = 1 To rsSerie.RecordCount
        'on initialise le curseur à 0 étant donné que les numéros d'ordre sont par série
        cursor = 0
        rsCandidats.Open "SELECT ID FROM CANDIDAT_TESTS " _
            & " WHERE NUM_SOUS_CENTRE = " & varTabSCE(2, j - 1) & " AND NUM_SERIE = " & varTabSerie(0, k - 1) _
            & " ORDER BY NOMS, DATE_DE_NAISSANCE", cnx, adOpenStatic, adLockOptimistic
        varTabCandidats = rsCandidats.GetRows

        nbCanddidats = rsCandidats.RecordCount
        nbJurys = RoundUp(nbCanddidats / 250)

        'On parcourt les jurys de la série k du sce j
        numJury = nbJurys
        For l = 1 To nbJurys
            jury = jury + 1

            If numJury > 1 Then
                'On parcourt les candidats du jury l pour leur attribuer le numéro d'ordre et le jury
                For m = 250 * (l - 1) + 1 To 250 * (l - 1) + 250
                    cursor = cursor + 1
                    rsUpdate.Open "UPDATE CANDIDAT_TESTS " _
                        & " SET NUMERO_ORDRE = " & cursor & ", JURY = " & jury _
                        & " WHERE ID = " & varTabCandidats(0, m - 1), cnx, adOpenStatic, adLockOptimistic

                    Set rsUpdate = Nothing
                Next m
            ElseIf numJury = 1 Then
                'On parcourt les candidats du dernier jury pour leur attribuer le numéro d'ordre et le jury
                For m = 250 * (l - 1) + 1 To nbCanddidats
                    cursor = cursor + 1
                    rsUpdate.Open "UPDATE CANDIDAT_TESTS " _
                        & " SET NUMERO_ORDRE = " & cursor & ", JURY = " & jury _
                        & " WHERE ID = " & varTabCandidats(0, m - 1), cnx, adOpenStatic, adLockOptimistic

                    Set rsUpdate = Nothing
                Next m
            End If
            numJury = numJury - 1

        Next l

        Set rsCandidats = Nothing
        Set rsSerie = Nothing
    Next k

    Set rsSCE = Nothing
Next j ´´´
</code>```

Is there any way I could transform the for m loop to a single query? Because I am looping this block of code again.

Thanks to y'all

答:
This is what i did:

```<code>dim popjury as integer, jurynum as integer

popjury=0
jurynum=1
Do Until rsCandidats.EOF
    cursor = cursor  + 1
    popjury=popjury+1
    if popjury > 250 then
          popjury=1
          jurynum=jurynum+1
    end if
    rsCandidats.Edit
    rsCandidats!NUMERO_ORDRE = cursor
    rsCandidats!JURY = jurynum
    rsCandidats.Update
    rsCandidats.MoveNext
Loop
</code>```

It works ! Thanks to y'all.

Body:
I am using MS Access vba as the interface and SQL Server as database server.

I want to update a set of rows in a table CANDIDAT_TESTS. What I am now doing is update one by one and I loop with a for loop; it works, but it takes too much time.

I would like to reduce the number of query by looping in one query.

My code:

This is the entire code

´´´ varSession = "2020"
    Set cnx = getConnectionBD(varSession)

rsSCE.Open "SELECT DISTINCT LIBELLE_DEPARTEMENT, LIBELLE_SOUS_CENTRE, NUM_SOUS_CENTRE " _
    & " FROM VIEW_CANDIDATS_SCE " _
    & " WHERE NUM_REGION = " & Me.LIST_REGION & " AND NUM_EXAMEN = " & Me.LIST_EXAMEN _
    & " ORDER BY LIBELLE_DEPARTEMENT, LIBELLE_SOUS_CENTRE", cnx, adOpenStatic, adLockOptimistic
varTabSCE = rsSCE.GetRows
'On initialise les jurys parce que les jurys sont par région
jury = 0

'On parcourt les sous-centres par départements
For j = 1 To rsSCE.RecordCount
    rsSerie.Open "SELECT DISTINCT NUM_SERIE, ABREVIATION_SERIE " _
        & " FROM VIEW_CANDIDATS_SCE " _
        & " WHERE NUM_SOUS_CENTRE = " & varTabSCE(2, j - 1) & " AND NUM_EXAMEN = " & Me.LIST_EXAMEN _
        & " ORDER BY ABREVIATION_SERIE", cnx, adOpenStatic, adLockOptimistic
    varTabSerie = rsSerie.GetRows

    'On parcourt les séries du sce j
    For k = 1 To rsSerie.RecordCount
        'on initialise le curseur à 0 étant donné que les numéros d'ordre sont par série
        cursor = 0
        rsCandidats.Open "SELECT ID FROM CANDIDAT_TESTS " _
            & " WHERE NUM_SOUS_CENTRE = " & varTabSCE(2, j - 1) & " AND NUM_SERIE = " & varTabSerie(0, k - 1) _
            & " ORDER BY NOMS, DATE_DE_NAISSANCE", cnx, adOpenStatic, adLockOptimistic
        varTabCandidats = rsCandidats.GetRows

        nbCanddidats = rsCandidats.RecordCount
        nbJurys = RoundUp(nbCanddidats / 250)

        'On parcourt les jurys de la série k du sce j
        numJury = nbJurys
        For l = 1 To nbJurys
            jury = jury + 1

            If numJury > 1 Then
                'On parcourt les candidats du jury l pour leur attribuer le numéro d'ordre et le jury
                For m = 250 * (l - 1) + 1 To 250 * (l - 1) + 250
                    cursor = cursor + 1
                    rsUpdate.Open "UPDATE CANDIDAT_TESTS " _
                        & " SET NUMERO_ORDRE = " & cursor & ", JURY = " & jury _
                        & " WHERE ID = " & varTabCandidats(0, m - 1), cnx, adOpenStatic, adLockOptimistic

                    Set rsUpdate = Nothing
                Next m
            ElseIf numJury = 1 Then
                'On parcourt les candidats du dernier jury pour leur attribuer le numéro d'ordre et le jury
                For m = 250 * (l - 1) + 1 To nbCanddidats
                    cursor = cursor + 1
                    rsUpdate.Open "UPDATE CANDIDAT_TESTS " _
                        & " SET NUMERO_ORDRE = " & cursor & ", JURY = " & jury _
                        & " WHERE ID = " & varTabCandidats(0, m - 1), cnx, adOpenStatic, adLockOptimistic

                    Set rsUpdate = Nothing
                Next m
            End If
            numJury = numJury - 1

        Next l

        Set rsCandidats = Nothing
        Set rsSerie = Nothing
    Next k

    Set rsSCE = Nothing
Next j ´´´

Is there any way I could transform the for m loop to a single query? Because I am looping this block of code again.

Thanks to y'all

Body:
This is what i did:

dim popjury as integer, jurynum as integer

popjury=0
jurynum=1
Do Until rsCandidats.EOF
    cursor = cursor  + 1
    popjury=popjury+1
    if popjury > 250 then
          popjury=1
          jurynum=jurynum+1
    end if
    rsCandidats.Edit
    rsCandidats!NUMERO_ORDRE = cursor
    rsCandidats!JURY = jurynum
    rsCandidats.Update
    rsCandidats.MoveNext
Loop

It works ! Thanks to y'all.


问:
UML help C# Design Principles
Could anyone please point out the meaning of the graph below:

What is the relationship between PolicyLayer and PolicyServiceInterface

What is the relationship between PolicyServiceInterface and MachanismLayer.

C# code would be also appreciated!

Please note that the UML is from Agile Principles, Patterns, and Practices in C#
By Martin C. Robert, Martin Micah 2006.

Added on 15 2011/6/2

Do the following have the same meaning:
1) A solid line with a triangle at one end
2) A dashed line with a triangle at one end

Added on 2011/6/3  1st

What is the difference between:
1) A solid line with an arrow at one end
2) A dashed line with an arrow at one end

Example in thie sample and PersistentObject and ThirdPartyPersistentSet in the link below:

UML help C# Design Principles

Added on 2011/6/3 2nd

Can the relationship between PolicyLayer and PolicyServiceInterface as below:

```<code>public class PolicyLayer

{
    private PolicyServiceInterface policyServiceInterface = new PolicyServiceInterfaceImplementation();
}

class PolicyServiceInterfaceImplementation:PolicyServiceInterface {}
</code>```

Regarding

答:
1) What is the relationship between PolicyLayer and PolicyServiceInterface

The -----> is Association ("knows a")

(source: sedris.org)

C# code:

```<code>public interface PolicyServiceInterface { }

public class PolicyLayer
{
    private IPolicyServiceInterface _policyServiceInterface;
    // Constructor Assocation
    public PolicyLayer(IPolicyServiceInterface policyServiceInterface)
    {
        _policyServiceInterface = policyServiceInterface;
    }
}
</code>```

2) What is the relationship between PolicyServiceInterface and MachanismLayer.

The - - -|> is Realization ("implements")

C# Code:

```<code>public interface PolicyServiceInterface { }

public class MachanismLayer : PolicyServiceInterface
</code>```

3) Do the following have the same meaning: 1) A solid line with a triangle at one end 2) A dashed line with a triangle at one end?

No they have different meanings:

The -----|> is Generalization ("inherits")

C# Code:

```<code>public class PolicyServiceInterface { } // could also be abstract

public class MachanismLayer : PolicyServiceInterface
</code>```

What is the difference between: 1) A solid line with an arrow at one end 2) A dashed line with an arrow at one end

The - - -> is Dependency ("uses a") There are various forms of dependency including local variables, parameter values, static function calls or return values.

C# Code:

```<code>// Here Foo is dependent on Baz
// That is Foo - - -> Baz
public class Foo {
   public int DoSomething() { // A form of local variable dependency
       Baz x = new Baz();
       return x.GetInt();
   }
}
</code>```

See my answer here for Composition and Aggregation.

Title: UML help C# Design Principles

Body:
Could anyone please point out the meaning of the graph below:

What is the relationship between PolicyLayer and PolicyServiceInterface

What is the relationship between PolicyServiceInterface and MachanismLayer.

C# code would be also appreciated!

Please note that the UML is from Agile Principles, Patterns, and Practices in C#
By Martin C. Robert, Martin Micah 2006.

Added on 15 2011/6/2

Do the following have the same meaning:
1) A solid line with a triangle at one end
2) A dashed line with a triangle at one end

Added on 2011/6/3  1st

What is the difference between:
1) A solid line with an arrow at one end
2) A dashed line with an arrow at one end

Example in thie sample and PersistentObject and ThirdPartyPersistentSet in the link below:

UML help C# Design Principles

Added on 2011/6/3 2nd

Can the relationship between PolicyLayer and PolicyServiceInterface as below:

public class PolicyLayer

{
    private PolicyServiceInterface policyServiceInterface = new PolicyServiceInterfaceImplementation();
}

class PolicyServiceInterfaceImplementation:PolicyServiceInterface {}

Regarding

Body:
1) What is the relationship between PolicyLayer and PolicyServiceInterface

The -----> is Association ("knows a")

(source: sedris.org)

C# code:

public interface PolicyServiceInterface { }

public class PolicyLayer
{
    private IPolicyServiceInterface _policyServiceInterface;
    // Constructor Assocation
    public PolicyLayer(IPolicyServiceInterface policyServiceInterface)
    {
        _policyServiceInterface = policyServiceInterface;
    }
}

2) What is the relationship between PolicyServiceInterface and MachanismLayer.

The - - -|> is Realization ("implements")

C# Code:

public interface PolicyServiceInterface { }

public class MachanismLayer : PolicyServiceInterface

3) Do the following have the same meaning: 1) A solid line with a triangle at one end 2) A dashed line with a triangle at one end?

No they have different meanings:

The -----|> is Generalization ("inherits")

C# Code:

public class PolicyServiceInterface { } // could also be abstract

public class MachanismLayer : PolicyServiceInterface

What is the difference between: 1) A solid line with an arrow at one end 2) A dashed line with an arrow at one end

The - - -> is Dependency ("uses a") There are various forms of dependency including local variables, parameter values, static function calls or return values.

C# Code:

// Here Foo is dependent on Baz
// That is Foo - - -> Baz
public class Foo {
   public int DoSomething() { // A form of local variable dependency
       Baz x = new Baz();
       return x.GetInt();
   }
}

See my answer here for Composition and Aggregation.


问:
C - How scanf inputs work and how it iterates in loops?
I know the basics of scanf(); requiring a conversion specifier % and an address to the variable to store the input value &.

While doing an assignment, there was a task that involved inputting an arbitrary number of values, one example would be:
5 4 3 2 1

Into scanf, and then print out number of symbols corresponding to the integer typed (eg. '?'), so it would display the terminal as:

```<code>5 4 3 2 1
?????
????
???
??
?
</code>```

In this case I had put the scanf in a while loop as so:

```<code>int i, num;
while(scanf("%d",&num)==1){
   printf("%d",num);
   for (i=0; i<num; i++){
      printf("?");
   }
   printf("/n");
}
</code>```

I am totally confused how scanf reads multiple integers in one input line (5 4 3 2 1) when many sources has specified that scanf only takes one integer until it reads a whitespace. From looking at this, my understanding is that the whitespace separating the integers indicate a new iteration following the previous integer?
When I tried to trace how printing works, it printed as:

```<code>5 4 3 2 1
5?????
4????
3???
2??
1?
</code>```

...So my question is how does scanf 'save' all these integers in one line to 'num' and print EACH of the corresponding symbols to the values given AFTER input? Wouldn't integers be replacing the previous in the variable without an array?

Sorry if this question does not make sense - still quite new to coding. Thank you!

答:
scanf 'reads' characters from the standard input stream stdin (if there is nothing there yet it prompts the user to type something to be added to it), and converts them to a format depending on the conversion specifiers used in the format string.

You can think about stdin as a sequence of characters in the memory, and every time the user types something in the terminal and presses Enter what was typed is added to the stdin.

So in your case, when you type 5 4 3 2 1 and presses Enter in the terminal, stdin will receive the sequence of characters "5 4 3 2 1\n" (notice that the new line character was added when you pressed Enter).

Then the scanf("%d",&num), which is expecting only 1 decimal integer number, 'reads' and 'consumes' from stdin the relevant characters that form one continuous decimal integer number.

In this case 5 is read the first time scanf is executed, and " 4 3 2 1\n" is left in the stdin. Then as the condition is satisfied the loop statements are executed. And the second time scanf is executed the leading space is discarded by the %d specifier and 4 is read, leaving " 3 2 1\n" in the stdin. And so on until no decimal integers numbers can be read from the stdin...

Body:
I know the basics of scanf(); requiring a conversion specifier % and an address to the variable to store the input value &.

While doing an assignment, there was a task that involved inputting an arbitrary number of values, one example would be:
5 4 3 2 1

Into scanf, and then print out number of symbols corresponding to the integer typed (eg. '?'), so it would display the terminal as:

5 4 3 2 1
?????
????
???
??
?

In this case I had put the scanf in a while loop as so:

int i, num;
while(scanf("%d",&num)==1){
   printf("%d",num);
   for (i=0; i<num; i++){
      printf("?");
   }
   printf("/n");
}

I am totally confused how scanf reads multiple integers in one input line (5 4 3 2 1) when many sources has specified that scanf only takes one integer until it reads a whitespace. From looking at this, my understanding is that the whitespace separating the integers indicate a new iteration following the previous integer?
When I tried to trace how printing works, it printed as:

5 4 3 2 1
5?????
4????
3???
2??
1?

...So my question is how does scanf 'save' all these integers in one line to 'num' and print EACH of the corresponding symbols to the values given AFTER input? Wouldn't integers be replacing the previous in the variable without an array?

Sorry if this question does not make sense - still quite new to coding. Thank you!


问:
Spirit X3, referring to a previously matched value
I'm writing a parser in Spirit X3 in order to get familiar with it, and even though I'm pretty familiar Qi I'm still hitting some stumbling blocks in X3.

For example, the Qi examples include a basic XML parser that should you how to match a previously matched value using Phoenix placeholders. However, I've only kinda been able to figure it out in X3:

```<code>#include <iostream>
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

namespace x3 = boost::spirit::x3;

namespace mytest
{

struct SimpleElement
{
    std::string tag;
    std::string content;
};

} // namespace bbspirit

BOOST_FUSION_ADAPT_STRUCT
(
    mytest::SimpleElement, tag, content
)

namespace mytest
{

namespace x3 = boost::spirit::x3;
namespace ascii = boost::spirit::x3::ascii;

using x3::lit;
using x3::lexeme;
using ascii::char_;

const x3::rule<class SimpleElementID, SimpleElement> simpleTag = "simpleTag";

auto assignTag = [](auto& ctx)
{
    x3::_val(ctx).tag = x3::_attr(ctx);
};

auto testTag = [](auto& ctx)
{
    x3::_pass(ctx) =
        (x3::_val(ctx).tag == x3::_attr(ctx));
};

auto assignContent = [](auto& ctx)
{
    x3::_val(ctx).content = x3::_attr(ctx);
};

auto const simpleTag_def
    = '['
    >> x3::lexeme[+(char_ - ']')][assignTag]
    >> ']'
    >> x3::lexeme[
        +(char_ - x3::lit("[/"))]
            [assignContent]
    >> "[/"
    >> x3::lexeme[+(char_ - ']')][testTag]
    >> ']'
    ;

BOOST_SPIRIT_DEFINE(simpleTag);

} // namespace bbspirit

int main()
{

const std::string text = "[test]Hello World![/test]";
std::string::const_iterator start = std::begin(text);
const std::string::const_iterator stop = std::end(text);

mytest::SimpleElement element{};

bool result =
    phrase_parse(start, stop, mytest::simpleTag, x3::ascii::space, element);

if (!result)
{
    std::cout << "failed to parse!\n";
}
else
{
    std::cout << "tag    : " << element.tag << '\n';
    std::cout << "content: " << element.content << '\n';
}

}
</code>```

(Link: https://wandbox.org/permlink/xLZN9plcOwkSKCrD )

This works, however if I try to parse something like [test]Hello [/World[/test] it doesn't work because I have not specified the correct omission here:

```<code>    >> x3::lexeme[
        +(char_ - x3::lit("[/"))]
            [assignContent]
</code>```

Essentially I want to tell the parser something like:

```<code>    >> x3::lexeme[
        +(char_ - (x3::lit("[/")  << *the start tag* << ']') )]
            [assignContent]
</code>```

How could I go about doing this? Also, is the way in which I'm referencing the start tag and later matching it the "best" way to do this in X3 or is there a better/more preferred way?

Thank you!

答:
Nice question.

The best answer would be to do exactly what XML does: outlaw [/ inside the tag data. In fact, XML outlaws < (because it could be opening a nested tag, and you don't want to have to potentially read-ahead the entire stream to find whether it is a valid subtag).

XML uses character entities ("escapes" like < and >) or unparsed character data (CDATA[]) to encode contents that requires these characters.

Next up, you can, of course do a negative lookahead assertion (!closeTag or -closeTag) using the tag attribute member like you already did.

Reshuffling the rule spelling a litte, it's not even that bad

Note I removed the need for manual propagation of the tag/contents using the , true> template argument on simpleTag rule. See Boost Spirit: "Semantic actions are evil"?

```<code>const x3::rule<class SimpleElementID, SimpleElement, true> simpleTag = "simpleTag";
auto testTag = [](auto& ctx) { _pass(ctx) = (_val(ctx).tag == _attr(ctx)); };

auto openTag     = '[' >> x3::lexeme[+(char_ - ']')] >> ']';
auto closeTag    = "[/" >> x3::lexeme[+(char_ - ']')] [testTag] >> ']';
auto tagContents = x3::lexeme[ +(char_ - closeTag) ];

auto const simpleTag_def
    =  openTag
    >> tagContents
    >> x3::omit [ closeTag ]
    ;
</code>```

See it Live On Coliru

Background

That works but ends up getting quite clumsy, because it means using semantic actions all around and also go against the natural binding of attribute references.

Thinking outside the box a litte:

In Qi you'd use qi::locals or inherited attributes for this (see a very similar example in the docs: MiniXML).

Both of these would have the net effect of extending the parser context with your piece(s) of information.

X3 has no such "high-level" features. But it does have the building block to extend your context: x3::witt<>(data) [ p ].

x3::with

In this simple example it would seem overkill, but at some point you will appreciate how you use extra context in your rules without holding your attribute types hostage:

```<code>struct TagName{};
auto openTag
    = x3::rule<struct openTagID, std::string, true> {"openTag"}
    = ('[' >> x3::lexeme[+(char_ - ']')] >> ']')
        [([](auto& ctx) { x3::get<TagName>(ctx) = _attr(ctx); })]
    ;
auto closeTag
    = x3::rule<struct closeTagID, std::string, true> {"closeTag"}
    = ("[/" >> x3::lexeme[+(char_ - ']')] >> ']')
        [([](auto& ctx) { _pass(ctx) = (x3::get<TagName>(ctx) == _attr(ctx)); })]
    ;
auto tagContents
    = x3::rule<struct openTagID, std::string> {"tagContents"}
    = x3::lexeme[ +(char_ - closeTag) ];

auto const simpleTag
    = x3::rule<class SimpleElementID, SimpleElement, true> {"simpleTag"}
    = x3::with<TagName>(std::string()) [
        openTag
        >> tagContents
        >> x3::omit [ closeTag ]
    ];
</code>```

See it Live On Coliru

Body:
I'm writing a parser in Spirit X3 in order to get familiar with it, and even though I'm pretty familiar Qi I'm still hitting some stumbling blocks in X3.

For example, the Qi examples include a basic XML parser that should you how to match a previously matched value using Phoenix placeholders. However, I've only kinda been able to figure it out in X3:

#include <iostream>
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

namespace x3 = boost::spirit::x3;

namespace mytest
{

struct SimpleElement
{
    std::string tag;
    std::string content;
};

} // namespace bbspirit

BOOST_FUSION_ADAPT_STRUCT
(
    mytest::SimpleElement, tag, content
)

namespace mytest
{

namespace x3 = boost::spirit::x3;
namespace ascii = boost::spirit::x3::ascii;

using x3::lit;
using x3::lexeme;
using ascii::char_;

const x3::rule<class SimpleElementID, SimpleElement> simpleTag = "simpleTag";

auto assignTag = [](auto& ctx)
{
    x3::_val(ctx).tag = x3::_attr(ctx);
};

auto testTag = [](auto& ctx)
{
    x3::_pass(ctx) =
        (x3::_val(ctx).tag == x3::_attr(ctx));
};

auto assignContent = [](auto& ctx)
{
    x3::_val(ctx).content = x3::_attr(ctx);
};

auto const simpleTag_def
    = '['
    >> x3::lexeme[+(char_ - ']')][assignTag]
    >> ']'
    >> x3::lexeme[
        +(char_ - x3::lit("[/"))]
            [assignContent]
    >> "[/"
    >> x3::lexeme[+(char_ - ']')][testTag]
    >> ']'
    ;

BOOST_SPIRIT_DEFINE(simpleTag);

} // namespace bbspirit

int main()
{

const std::string text = "[test]Hello World![/test]";
std::string::const_iterator start = std::begin(text);
const std::string::const_iterator stop = std::end(text);

mytest::SimpleElement element{};

bool result =
    phrase_parse(start, stop, mytest::simpleTag, x3::ascii::space, element);

if (!result)
{
    std::cout << "failed to parse!\n";
}
else
{
    std::cout << "tag    : " << element.tag << '\n';
    std::cout << "content: " << element.content << '\n';
}

}

(Link: https://wandbox.org/permlink/xLZN9plcOwkSKCrD )

This works, however if I try to parse something like [test]Hello [/World[/test] it doesn't work because I have not specified the correct omission here:

    >> x3::lexeme[
        +(char_ - x3::lit("[/"))]
            [assignContent]

Essentially I want to tell the parser something like:

    >> x3::lexeme[
        +(char_ - (x3::lit("[/")  << *the start tag* << ']') )]
            [assignContent]

How could I go about doing this? Also, is the way in which I'm referencing the start tag and later matching it the "best" way to do this in X3 or is there a better/more preferred way?

Thank you!

Body:
Nice question.

The best answer would be to do exactly what XML does: outlaw [/ inside the tag data. In fact, XML outlaws < (because it could be opening a nested tag, and you don't want to have to potentially read-ahead the entire stream to find whether it is a valid subtag).

XML uses character entities ("escapes" like &lt; and &gt;) or unparsed character data (CDATA[]) to encode contents that requires these characters.

Next up, you can, of course do a negative lookahead assertion (!closeTag or -closeTag) using the tag attribute member like you already did.

Reshuffling the rule spelling a litte, it's not even that bad

Note I removed the need for manual propagation of the tag/contents using the , true> template argument on simpleTag rule. See Boost Spirit: "Semantic actions are evil"?

const x3::rule<class SimpleElementID, SimpleElement, true> simpleTag = "simpleTag";
auto testTag = [](auto& ctx) { _pass(ctx) = (_val(ctx).tag == _attr(ctx)); };

auto openTag     = '[' >> x3::lexeme[+(char_ - ']')] >> ']';
auto closeTag    = "[/" >> x3::lexeme[+(char_ - ']')] [testTag] >> ']';
auto tagContents = x3::lexeme[ +(char_ - closeTag) ];

auto const simpleTag_def
    =  openTag
    >> tagContents
    >> x3::omit [ closeTag ]
    ;

See it Live On Coliru

Background

That works but ends up getting quite clumsy, because it means using semantic actions all around and also go against the natural binding of attribute references.

Thinking outside the box a litte:

In Qi you'd use qi::locals or inherited attributes for this (see a very similar example in the docs: MiniXML).

Both of these would have the net effect of extending the parser context with your piece(s) of information.

X3 has no such "high-level" features. But it does have the building block to extend your context: x3::witt<>(data) [ p ].

x3::with

In this simple example it would seem overkill, but at some point you will appreciate how you use extra context in your rules without holding your attribute types hostage:

struct TagName{};
auto openTag
    = x3::rule<struct openTagID, std::string, true> {"openTag"}
    = ('[' >> x3::lexeme[+(char_ - ']')] >> ']')
        [([](auto& ctx) { x3::get<TagName>(ctx) = _attr(ctx); })]
    ;
auto closeTag
    = x3::rule<struct closeTagID, std::string, true> {"closeTag"}
    = ("[/" >> x3::lexeme[+(char_ - ']')] >> ']')
        [([](auto& ctx) { _pass(ctx) = (x3::get<TagName>(ctx) == _attr(ctx)); })]
    ;
auto tagContents
    = x3::rule<struct openTagID, std::string> {"tagContents"}
    = x3::lexeme[ +(char_ - closeTag) ];

auto const simpleTag
    = x3::rule<class SimpleElementID, SimpleElement, true> {"simpleTag"}
    = x3::with<TagName>(std::string()) [
        openTag
        >> tagContents
        >> x3::omit [ closeTag ]
    ];

See it Live On Coliru


问:
How can I define a UNIQUE constraint that applies to multiple columns in a DataSet table?
I have the following table defined in a .sql script file.

```<code>CREATE TABLE [HwComponent](
    [HwComponentId] [int] NOT NULL,
    [HwComponentTypeId] [int] NOT NULL,
    [ManufactureId] [int] NOT NULL,
    [SerialNumber] [nvarchar](100) NOT NULL,
    [AssignmentType] [nvarchar](1000) NOT NULL,
    [IsFunctional] [nvarchar](10) NOT NULL,
    [Note] [nvarchar](4000) NULL,

    CONSTRAINT [PK_HwComponent] PRIMARY KEY ([HwComponentId]),
    CONSTRAINT (FK1_HwComponent] FOREIGN KEY ([HwComponentTypeId]) REFERENCES [HwComponentType] ([HwComponentTypeId)] ON DELETE NO ACTION ON UPDATE NO ACTION
    CONSTRAINT (FK2_HwComponent] FOREIGN KEY ([HwComponentTypeId], [ManufactureId]) REFERENCES [HwComponentTypeManufacturerInfo] ([HwComponentTypeId], [ManufactureId]) ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT (UI1_HwComponent] UNIQUE ([HwComponentTypeId], [ManufactureId], [SerialNumber]))

GO
</code>```

I now need to define a new table in the DataSet Designer to match.

I believe I have everything defined correctly, except the UNIQUE constraint that requires all 3 columns be considered together as the unique constraint.

How do I define the UNIQUE constraint for this table in the DataSet Designer?

SQL CE Service 4.0 SP1:
VS Prof 2017 - Version 15.8.7

答:
Your code should work if properly formatted.  You have parens where you shouldn't:

```<code>CREATE TABLE [HwComponent](
    [HwComponentId] [int] NOT NULL,
    [HwComponentTypeId] [int] NOT NULL,
    [ManufactureId] [int] NOT NULL,
    [SerialNumber] [nvarchar](100) NOT NULL,
    [AssignmentType] [nvarchar](1000) NOT NULL,
    [IsFunctional] [nvarchar](10) NOT NULL,
    [Note] [nvarchar](4000) NULL,

    CONSTRAINT PK_HwComponent PRIMARY KEY ([HwComponentId]),
    CONSTRAINT FK1_HwComponent FOREIGN KEY ([HwComponentTypeId]) REFERENCES [HwComponentType] ([HwComponentTypeId)] ON DELETE NO ACTION ON UPDATE NO ACTION
    CONSTRAINT K2_HwComponent FOREIGN KEY ([HwComponentTypeId], [ManufactureId]) REFERENCES [HwComponentTypeManufacturerInfo] ([HwComponentTypeId], [ManufactureId]) ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT UI1_HwComponent UNIQUE ([HwComponentTypeId], [ManufactureId], [SerialNumber])
);
</code>```

I would advise you to get rid of all the square braces.  They just make the code harder to write and to read and to modify.

Body:
I have the following table defined in a .sql script file.

CREATE TABLE [HwComponent](
    [HwComponentId] [int] NOT NULL,
    [HwComponentTypeId] [int] NOT NULL,
    [ManufactureId] [int] NOT NULL,
    [SerialNumber] [nvarchar](100) NOT NULL,
    [AssignmentType] [nvarchar](1000) NOT NULL,
    [IsFunctional] [nvarchar](10) NOT NULL,
    [Note] [nvarchar](4000) NULL,

    CONSTRAINT [PK_HwComponent] PRIMARY KEY ([HwComponentId]),
    CONSTRAINT (FK1_HwComponent] FOREIGN KEY ([HwComponentTypeId]) REFERENCES [HwComponentType] ([HwComponentTypeId)] ON DELETE NO ACTION ON UPDATE NO ACTION
    CONSTRAINT (FK2_HwComponent] FOREIGN KEY ([HwComponentTypeId], [ManufactureId]) REFERENCES [HwComponentTypeManufacturerInfo] ([HwComponentTypeId], [ManufactureId]) ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT (UI1_HwComponent] UNIQUE ([HwComponentTypeId], [ManufactureId], [SerialNumber]))

GO

I now need to define a new table in the DataSet Designer to match.

I believe I have everything defined correctly, except the UNIQUE constraint that requires all 3 columns be considered together as the unique constraint.

How do I define the UNIQUE constraint for this table in the DataSet Designer?

SQL CE Service 4.0 SP1:
VS Prof 2017 - Version 15.8.7

Body:
Your code should work if properly formatted.  You have parens where you shouldn't:

CREATE TABLE [HwComponent](
    [HwComponentId] [int] NOT NULL,
    [HwComponentTypeId] [int] NOT NULL,
    [ManufactureId] [int] NOT NULL,
    [SerialNumber] [nvarchar](100) NOT NULL,
    [AssignmentType] [nvarchar](1000) NOT NULL,
    [IsFunctional] [nvarchar](10) NOT NULL,
    [Note] [nvarchar](4000) NULL,

    CONSTRAINT PK_HwComponent PRIMARY KEY ([HwComponentId]),
    CONSTRAINT FK1_HwComponent FOREIGN KEY ([HwComponentTypeId]) REFERENCES [HwComponentType] ([HwComponentTypeId)] ON DELETE NO ACTION ON UPDATE NO ACTION
    CONSTRAINT K2_HwComponent FOREIGN KEY ([HwComponentTypeId], [ManufactureId]) REFERENCES [HwComponentTypeManufacturerInfo] ([HwComponentTypeId], [ManufactureId]) ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT UI1_HwComponent UNIQUE ([HwComponentTypeId], [ManufactureId], [SerialNumber])
);

I would advise you to get rid of all the square braces.  They just make the code harder to write and to read and to modify.


问:
How to make my function more maintainable with Object.entries method in React
When I loop through objects it should apply specific requirements. Therefore I have written two seperate functions which do the job as I want, but noticed the code below is not DRY, so want to look for a cleaner, more maintainable and reusable way to do that.

// get all ingredients clustered in one array
    const parsedIngredients = Object.entries(meal).reduce(
        (ingredients, [key, value]) => {
            if (key.includes("Measure") && value !== "" && value !== null) {
                const keyReference = key.match(/\d+/)[0];
                const ingredient = meal[`strIngredient${keyReference}`];
                ingredients.push(`${value} ${ingredient}`);
            }
            return ingredients;
        },
        []
    );
    const YoutubeID = Object.entries(meal).reduce(
        (currentYoutubeId, [key, value]) => {
            if(key.includes("strYoutube") && value !== "") {
                const getYoutTubeId = value.split('=').pop();
                currentYoutubeId.push(`${getYoutTubeId}`);
            }
            return currentYoutubeId
        },
        []
    );

    export default meal = [{"idMeal":"52941","strMeal":"Red Peas Soup","strDrinkAlternate":null,"strCategory":"Beef","strArea":"Jamaican","strInstructions":"Wash and rinse the dried kidney beans.. then cover with water in a deep bowl. Remember as they soak they will expand to at least triple the size they were originally so add a lot of water to the bowl. Soak them overnight or for at least 2 hrs to make the cooking step go quicker. I tossed out the water they were soaked in after it did the job.\r\n\r\nHave your butcher cut the salted pigtail into 2 inch pieces as it will be very difficult to cut with an ordinary kitchen knife. Wash, then place a deep pot with water and bring to a boil. Cook for 20 minutes, then drain + rinse and repeat (boil again in water). The goal is to make the pieces of pig tails tender and to remove most of the salt it was cured in.\r\n\r\nTime to start the soup. Place everything in the pot (except the flour and potato), then cover with water and place on a high flame to bring to a boil. As it comes to a boil, skim off any scum\/froth at the top and discard. Reduce the heat to a gentle boil and allow it to cook for 1 hr and 15 mins.. basically until the beans are tender and start falling apart.\r\n\r\nIt\u2019s now time to add the potato (and Yams etc if you\u2019re adding it) as well as the coconut milk and continue cooking for 15 minutes.\r\n\r\nNow is a good time to start making the basic dough for the spinner dumplings. Mix the flour and water (add a pinch of salt if you want) until you have a soft\/smooth dough. allow it to rest for 5 minutes, then pinch of a tablespoon at a time and roll between your hands to form a cigarette shape.\r\n\r\nAdd them to the pot, stir well and continue cooking for another 15 minutes on a rolling boil.\r\n\r\nYou\u2019ll notice that I didn\u2019t add any salt to the pot as the remaining salt from the salted pigtails will be enough to properly season this dish. However you can taste and adjust accordingly. Lets recap the timing part of things so you\u2019re not confused. Cook the base of the soup for 1 hr and 15 minute or until tender, then add the potatoes and cook for 15 minutes, then add the dumplings and cook for a further 15 minutes. Keep in mind that this soup will thicken quite a bit as it cools.\r\n\r\nWhile this is not a traditional recipe to any one specific island, versions of this soup (sometimes called stewed peas) can be found throughout the Caribbean, Latin America and Africa. A hearty bowl of this soup will surely give you the sleepies (some may call it ethnic fatigue). You can certainly freeze the leftovers and heat it up another day.","strMealThumb":"https:\/\/www.themealdb.com\/images\/media\/meals\/sqpqtp1515365614.jpg","strTags":"Soup,SideDish","strYoutube":"https:\/\/www.youtube.com\/watch?v=1ogCfDXotMw","strIngredient1":"Kidney Beans","strIngredient2":"Carrots","strIngredient3":"Spring Onions","strIngredient4":"Thyme","strIngredient5":"Onion","strIngredient6":"Black Pepper","strIngredient7":"Red Pepper","strIngredient8":"Garlic Clove","strIngredient9":"Allspice","strIngredient10":"Beef","strIngredient11":"Water","strIngredient12":"Potatoes","strIngredient13":"Plain Flour","strIngredient14":"Water","strIngredient15":"Coconut Milk","strIngredient16":"","strIngredient17":"","strIngredient18":"","strIngredient19":"","strIngredient20":"","strMeasure1":"2 cups ","strMeasure2":"1 large","strMeasure3":"2 chopped","strMeasure4":"4 sprigs","strMeasure5":"1 Diced","strMeasure6":"1\/2 tsp","strMeasure7":"2 chopped","strMeasure8":"4 Mashed","strMeasure9":"1 tbs","strMeasure10":"2 Lbs","strMeasure11":"2L","strMeasure12":"4","strMeasure13":"1 cup ","strMeasure14":"1\/4 cup","strMeasure15":"1 cup ","strMeasure16":"","strMeasure17":"","strMeasure18":"","strMeasure19":"","strMeasure20":"","strSource":"http:\/\/caribbeanpot.com\/caribbean-red-peas-soup\/","dateModified":null}]```

答:
You can extract logic which process values to a function

Example

const meal = {
  Measure1: "Measure1",
  strIngredient1: "1",
  Measure2: "Measure2",
  strIngredient2: "2",
  strYoutube1: "=1234",
  strYoutube2: "=2345",
  strYoutube3: "=2345"
}

const extractValues = (obj, rules) => {
  return Object.entries(obj).reduce((acc, [key, value]) => {

    for (let [ruleKey, func] of Object.entries(rules)) {
      const result = func(key, value);

      if (result) {
        acc[ruleKey] = [...(acc[ruleKey] || []), result]
      }

    }

    return acc;

  }, {})
}

const rules = {
  parsedIngredients: (key, value) => {
    if (key.includes("Measure") && value) {
      const keyReference = key.match(/\d+/)[0];

      const ingredient = meal[`strIngredient${keyReference}`];
      return `${value} ${ingredient}`;
    }
  },
  youtubeIds: (key, value) => {
    if (key.includes("strYoutube") && value) {
      const getYoutTubeId = value.split('=').pop();
      return `${getYoutTubeId}`;
    }
  }
}

const {
  parsedIngredients,
  youtubeIds
} = extractValues(meal, rules);

console.log(parsedIngredients, youtubeIds);```