问:
Attribute Error in Partial function used in multiprocessing application
I am trying to use multiprocessing.map on an iterable of iterables. I am using partial because I have other arguments that need to be input, but am getting an attribute error that the original partial function is not being recognized.

```<code>import multiprocessing as mp
from functools import partial

def g(y, x ):
    return x[0] + x[1] + y

z = partial(g, y=1)

pool = mp.Pool(2)
print(pool.map(z, [(1, 2,), (2, 3, ), (3, 4,)]))
</code>```

I am wondering why this is and what I am doing wrong, I have tried flipping the argument position, among other things. Thanks!

答:
Looking at the partial documentation, If more arguments are supplied to the call, they are appended to args. Its subtle, but it means that you can't set leading arguments by name with partial and then use positional arguments. Removing multiprocessing, your problem is reproducible with

```<code>>>> import multiprocessing as mp
>>> from functools import partial
>>>
>>> def g(y, x ):
...     return x[0] + x[1] + y
...
>>> z = partial(g, y=1)
>>>
>>> z((1,2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: g() got multiple values for argument 'y'
</code>```

The partial has args=(,) and kwargs={"y":1}. When called, the positional arguments are appended to args. In effect, the call is

```<code>>>> g((1,2), y=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: g() got multiple values for argument 'y'
</code>```

The argument you hoped would be x became the first positional argument y and you also tried to define as y=1. In this case you can fix the problem by setting a positional argument, not a keyword argument.

```<code>>>> z = partial(g, 1)
>>> z((1,2))
4
</code>```

That works because args=(1,), which is the y you wanted to set. On each call the positional argument is appended, becoming x. But it only works because you are replacing the first positional arguments. It wouldn't work in the more general case where some positional arguments are set and others are not.

Going back to the original script with multiprocessing, the solution still works. z is just an instance of the functools.partial class whose __call__ method uses the instance's args, keywords and func attributes to make the call. (added code to set multiprocessing type so that windows spawn can be tested on linux)

```<code>import multiprocessing as mp
from functools import partial
import sys

def g(y, x ):
    return x[0] + x[1] + y

z = partial(g, 1)

if __name__ == "__main__":
    if len(sys.argv) > 1:
        # optional start method for, spawn, forkserver
        mp.set_start_method(sys.argv[1])
    pool = mp.Pool(2)
    print(pool.map(z, [(1, 2,), (2, 3, ), (3, 4,)]))
</code>```

Output

```<code>[4, 6, 8]
</code>```

Body:
I am trying to use multiprocessing.map on an iterable of iterables. I am using partial because I have other arguments that need to be input, but am getting an attribute error that the original partial function is not being recognized.

import multiprocessing as mp
from functools import partial

def g(y, x ):
    return x[0] + x[1] + y

z = partial(g, y=1)

pool = mp.Pool(2)
print(pool.map(z, [(1, 2,), (2, 3, ), (3, 4,)]))

I am wondering why this is and what I am doing wrong, I have tried flipping the argument position, among other things. Thanks!

Body:
Looking at the partial documentation, If more arguments are supplied to the call, they are appended to args. Its subtle, but it means that you can't set leading arguments by name with partial and then use positional arguments. Removing multiprocessing, your problem is reproducible with

>>> import multiprocessing as mp
>>> from functools import partial
>>>
>>> def g(y, x ):
...     return x[0] + x[1] + y
...
>>> z = partial(g, y=1)
>>>
>>> z((1,2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: g() got multiple values for argument 'y'

The partial has args=(,) and kwargs={"y":1}. When called, the positional arguments are appended to args. In effect, the call is

>>> g((1,2), y=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: g() got multiple values for argument 'y'

The argument you hoped would be x became the first positional argument y and you also tried to define as y=1. In this case you can fix the problem by setting a positional argument, not a keyword argument.

>>> z = partial(g, 1)
>>> z((1,2))
4

That works because args=(1,), which is the y you wanted to set. On each call the positional argument is appended, becoming x. But it only works because you are replacing the first positional arguments. It wouldn't work in the more general case where some positional arguments are set and others are not.

Going back to the original script with multiprocessing, the solution still works. z is just an instance of the functools.partial class whose __call__ method uses the instance's args, keywords and func attributes to make the call. (added code to set multiprocessing type so that windows spawn can be tested on linux)

import multiprocessing as mp
from functools import partial
import sys

def g(y, x ):
    return x[0] + x[1] + y

z = partial(g, 1)

if __name__ == "__main__":
    if len(sys.argv) > 1:
        # optional start method for, spawn, forkserver
        mp.set_start_method(sys.argv[1])
    pool = mp.Pool(2)
    print(pool.map(z, [(1, 2,), (2, 3, ), (3, 4,)]))

Output

[4, 6, 8]


来源: stackexchange

问:
INSERT INTO database table, from form not working. SQL
lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):

"Connected to databaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test' ('name') VALUES ('daniel')' at line 1"

The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?

Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.

HTML

```<code><form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>
</code>```

PHP (insert.php)

```<code><?php
$dbhost  = 'localhost';
$dbname  = 'carbon_db';
$dbuser  = 'username';
$dbpass  = 'password';

$con = mysql_connect($dbhost, $dbuser, $dbpass);

if($con == FALSE)
{
    echo 'Cannot connect to database' . mysql_error();
}
else
{
    echo 'Connected to database';
}

mysql_select_db($dbname, $con);

$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";

if (!mysql_query($sql, $con))
{
    die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>
</code>```

答:
try using  ` instead of ' when refering to table/column names</p>

```<code>$sql="INSERT INTO `test` (`name`)
VALUES ('$_POST[namefield]')";
</code>```

ContentLicense: CC BY-SA 3.0

Body:
lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):

"Connected to databaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test' ('name') VALUES ('daniel')' at line 1"

The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?

Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.

HTML

<form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>

PHP (insert.php)

<?php
$dbhost  = 'localhost';
$dbname  = 'carbon_db';
$dbuser  = 'username';
$dbpass  = 'password';

$con = mysql_connect($dbhost, $dbuser, $dbpass);

if($con == FALSE)
{
    echo 'Cannot connect to database' . mysql_error();
}
else
{
    echo 'Connected to database';
}

mysql_select_db($dbname, $con);

$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";

if (!mysql_query($sql, $con))
{
    die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>

Body:
try using  ` instead of ' when refering to table/column names

$sql="INSERT INTO `test` (`name`)
VALUES ('$_POST[namefield]')";


问:
How do I remove a submodule?
How do I remove a Git submodule?
Why can't I do
git submodule rm module_name?

答:
If you want to remove the submodule without deleting the folder from your local file system here is what worked for me:

MOD=example
git rm --cached -f apps/$MOD
git config -f .gitmodules --remove-section submodule.$MOD
```

ContentLicense: CC BY-SA 4.0

Title: How do I remove a submodule?


问:
Auto resize grid cols when less number specified - tailwind
So, I am using tailwind grid, I have specified 6 cols for each row, though if the number of elements are less than 6, I want it to resize it to 3.

```<code><div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 grid-flow-row gap-2">
{data.map((d)=><SomeComponent/ d={d}>)}
</div>
</code>```

Additionally, I want that they should take n/kth width only if n is the number of current columns and k is the total columns in each grid row.

答:
You can try changing the Tailwind classes dynamically, for example:</p>
```<code><div className={"w-full grid lg:w-auto" + (condition ? 'grid-cols-3' : 'grid-cols-6')}>
</code>```

Body:
So, I am using tailwind grid, I have specified 6 cols for each row, though if the number of elements are less than 6, I want it to resize it to 3.

{data.map((d)=><SomeComponent/ d={d}>)}

Additionally, I want that they should take n/kth width only if n is the number of current columns and k is the total columns in each grid row.

Body:
You can try changing the Tailwind classes dynamically, for example:

<div className={"w-full grid lg:w-auto" + (condition ? 'grid-cols-3' : 'grid-cols-6')}>


问:
Checking a cell in pandas for 0, with different types of cell content
I'm trying to do an if where I check whether a cell is 0, the problem is that sometimes the cell will have a float, an array or just a 0.

I've done

```<code>if df.iat[i,df.columns.get_loc('B')] == 0:
     print('something')
</code>```

that gives me an error when there is an array:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

To try and solve that I tried:

```<code>if df.iat[i,df.columns.get_loc('B')].all() == 0:
     print('something')
</code>```

which arises the error

AttributeError: 'float' object has no attribute 'all'*, when the content of the cell is a float

Any ideas how can I work around this issue?

答:
Because column "B" contains values of different types, you'll need to check for data type first before evaluating if the value is equal to some value. So for example, if df.iat[i,df.columns.get_loc('B')] is equal to [1,2], then

```<code>df.iat[i,df.columns.get_loc('B')] == 0
</code>```

is equivalent to [1,2] == 0 which doesn't make sense.

You can check the data type first before checking if it's equal to 0 or not.

```<code>x = df.iat[i,df.columns.get_loc('B')]
if isinstance(x, (int,float)) and x == 0:
    # do something
else:
    # do something else
</code>```

Also, if you want to do the same check on the entire column (assuming you want to create a boolean list), you can use a list comprehension where you do a check the data type as well as if it's equal to 0 or not:

```<code>out = [True if isinstance(x, (int,float)) and x==0 else False for x in df['B']]
</code>```

You can assign it to a column as well:

```<code>df['zeros'] = out
</code>```

Body:
I'm trying to do an if where I check whether a cell is 0, the problem is that sometimes the cell will have a float, an array or just a 0.

I've done

if df.iat[i,df.columns.get_loc('B')] == 0:
     print('something')

that gives me an error when there is an array:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

To try and solve that I tried:

if df.iat[i,df.columns.get_loc('B')].all() == 0:
     print('something')

which arises the error

AttributeError: 'float' object has no attribute 'all'*, when the content of the cell is a float

Any ideas how can I work around this issue?

Body:
Because column "B" contains values of different types, you'll need to check for data type first before evaluating if the value is equal to some value. So for example, if df.iat[i,df.columns.get_loc('B')] is equal to [1,2], then

df.iat[i,df.columns.get_loc('B')] == 0

is equivalent to [1,2] == 0 which doesn't make sense.

You can check the data type first before checking if it's equal to 0 or not.

x = df.iat[i,df.columns.get_loc('B')]
if isinstance(x, (int,float)) and x == 0:
    # do something
else:
    # do something else

Also, if you want to do the same check on the entire column (assuming you want to create a boolean list), you can use a list comprehension where you do a check the data type as well as if it's equal to 0 or not:

out = [True if isinstance(x, (int,float)) and x==0 else False for x in df['B']]

You can assign it to a column as well:

df['zeros'] = out


问:
Enabling search feature in google maps using Android Studio
I was trying to implement a simple search bar in google maps that points the map's camera to the location that is entered in the search box, I've attached the code but whenever I run it, The application ends up crashing. The code is given below. (Also I'm new to Android Development, Please do help me out).</p>
```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private static final int REQUEST_LOCATION_PERMISSION = 1009;
    private GoogleMap mMap;
    private ActivityMapsBinding binding;
    private FusedLocationProviderClient mFusedLocationClient;
    //These Clusters were used to manage the marker Clusters that had images on maps too
    private ClusterManager mClusterManager;
    //Same is the case with these clusters
    private MyClusterManagerRenderer myClusterManagerRenderer;
    //Instantiating the Firestore Database
    FirebaseFirestore db;

    // creating a variable
    // for search view.
    SearchView searchView;

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

        // initializing our search view.
        searchView = findViewById(R.id.idSearchView);

        // initializing our firebase firestore.
        db = FirebaseFirestore.getInstance();

        binding = ActivityMapsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        //Getting the device location over here
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        // 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);

        //***** Searching Part starts from here*********
        // adding on query listener for our search view.
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // on below line we are getting the
                // location name from search view.
                String location = searchView.getQuery().toString();

                // below line is to create a list of address
                // where we will store the list of all address.
                List<Address> addressList = null;

                // checking if the entered location is null or not.
                if (location != null || location.equals("")) {
                    // on below line we are creating and initializing a geo coder.
                    Geocoder geocoder = new Geocoder(MapsActivity.this);
                    try {
                        // on below line we are getting location from the
                        // location name and adding that location to address list.
                        addressList = geocoder.getFromLocationName(location, 1);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    // on below line we are getting the location
                    // from our list a first position.
                    Address address = addressList.get(0);

                    // on below line we are creating a variable for our location
                    // where we will add our locations latitude and longitude.
                    LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());

                    // on below line we are adding marker to that position.
                    mMap.addMarker(new MarkerOptions().position(latLng).title(location));

                    // below line is to animate camera to that position.
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
                }
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        // at last we calling our map fragment to update.
        mapFragment.getMapAsync(this);

    }

    private void addMapMarkers(){

    }

    private void getLastKnownLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                if(task.isSuccessful()){
                    Location location = task.getResult();

                }
            }
        });
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // creating a variable for document reference.
        DocumentReference documentReference = db.collection("MapsData").document("7QWDor9vozLaHdFYV9kh");

        // calling document reference class with on snap shot listener.
        documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
                if (value != null && value.exists()) {
                    // below line is to create a geo point and we are getting
                    // geo point from firebase and setting to it.
                    GeoPoint geoPoint = value.getGeoPoint("geoPoint");

                    // getting latitude and longitude from geo point
                    // and setting it to our location.
                    LatLng location = new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude());

                    // adding marker to each location on google maps
                    mMap.addMarker(new MarkerOptions().position(location).title("Name"));

                    // below line is use to move camera.
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
                } else {
                    Toast.makeText(MapsActivity.this, "Error found is " + error, Toast.LENGTH_SHORT).show();
                }
            }
        });

        //Adding custom maps style over here
        //******** THIS PART OF CODE EXCLUSIVELY DESIGNED TO FETCH THE CUSTOM MAPS.JSON TEMPLATE**********
        enableMyLocation();

        try {
            // Customise the styling of the base map using a JSON object defined
            // in a raw resource file.
            boolean success = googleMap.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(
                            this, R.raw.mapstyle));
            if (!success) {
                Log.e("MapsActivity", "Style parsing failed.");
            }
            } catch (Resources. NotFoundException e) {
            Log.e("MapsActivity", "Can't find style. Error: ", e);
        }
        //******** MAP STYLING CODE ENDS OVER HERE **********

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        LatLng islamabad = new LatLng(33.68, 73.04);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Islamabad"));
        //moving the camera position to Islamabad.
        mMap.moveCamera(CameraUpdateFactory.newLatLng(islamabad));

    }

    //Getting the Users current Location

    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {
            ActivityCompat.requestPermissions(this, new String[]
                            {Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_LOCATION_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        // Check if location permissions are granted and if so enable the
        // location data layer.
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_LOCATION_PERMISSION:
                if (grantResults.length > 0
                        && grantResults[0]
                        == PackageManager.PERMISSION_GRANTED) {
                    enableMyLocation();
                    break;
                }
        }
    }
}
</code>```

答:
Instead of implementing a SearchView, add the places API from google in your grade file as follows:

```<code>implementation 'com.google.android.libraries.places:places:2.3.0'
</code>```

and use AutocompleteSupportFragment as follows:

```<code>try {
                    if (!Places.isInitialized()) {
                        Places.initialize(getActivity().getApplicationContext(), GlobalVariables.google_api_key);
                    }
  // Initialize the AutocompleteSupportFragment.
    AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment) getChildFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

        autocompleteFragment.getView().setBackground(ContextCompat.getDrawable(getContext(), R.drawable.bginfo_whit));
        autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG));
        autocompleteFragment.setCountry("ET");
        autocompleteFragment.setMenuVisibility(false);
        autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
             @Override
                public void onPlaceSelected(Place place) {
                    // TODO: Get info about the selected place.
                    LatLng newLatLng = place.getLatLng();
                     mMap.moveCamera(CameraUpdateFactory.newLatLng(newLatLng));
                     mMap.animateCamera(CameraUpdateFactory.zoomTo(17));
                    }

            @Override
                 public void onError(Status status) {
                    // TODO: Handle the error.
                     //Log.i(TAG, "An error occurred: " + status);
                    }

                 });
                }
                catch (Exception e)
                {}
</code>```

Body:
I was trying to implement a simple search bar in google maps that points the map's camera to the location that is entered in the search box, I've attached the code but whenever I run it, The application ends up crashing. The code is given below. (Also I'm new to Android Development, Please do help me out).

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private static final int REQUEST_LOCATION_PERMISSION = 1009;
    private GoogleMap mMap;
    private ActivityMapsBinding binding;
    private FusedLocationProviderClient mFusedLocationClient;
    //These Clusters were used to manage the marker Clusters that had images on maps too
    private ClusterManager mClusterManager;
    //Same is the case with these clusters
    private MyClusterManagerRenderer myClusterManagerRenderer;
    //Instantiating the Firestore Database
    FirebaseFirestore db;

    // creating a variable
    // for search view.
    SearchView searchView;

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

        // initializing our search view.
        searchView = findViewById(R.id.idSearchView);

        // initializing our firebase firestore.
        db = FirebaseFirestore.getInstance();

        binding = ActivityMapsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        //Getting the device location over here
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        // 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);

        //***** Searching Part starts from here*********
        // adding on query listener for our search view.
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // on below line we are getting the
                // location name from search view.
                String location = searchView.getQuery().toString();

                // below line is to create a list of address
                // where we will store the list of all address.
                List<Address> addressList = null;

                // checking if the entered location is null or not.
                if (location != null || location.equals("")) {
                    // on below line we are creating and initializing a geo coder.
                    Geocoder geocoder = new Geocoder(MapsActivity.this);
                    try {
                        // on below line we are getting location from the
                        // location name and adding that location to address list.
                        addressList = geocoder.getFromLocationName(location, 1);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    // on below line we are getting the location
                    // from our list a first position.
                    Address address = addressList.get(0);

                    // on below line we are creating a variable for our location
                    // where we will add our locations latitude and longitude.
                    LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());

                    // on below line we are adding marker to that position.
                    mMap.addMarker(new MarkerOptions().position(latLng).title(location));

                    // below line is to animate camera to that position.
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
                }
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        // at last we calling our map fragment to update.
        mapFragment.getMapAsync(this);

    }

    private void addMapMarkers(){

    }

    private void getLastKnownLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                if(task.isSuccessful()){
                    Location location = task.getResult();

                }
            }
        });
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // creating a variable for document reference.
        DocumentReference documentReference = db.collection("MapsData").document("7QWDor9vozLaHdFYV9kh");

        // calling document reference class with on snap shot listener.
        documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
                if (value != null && value.exists()) {
                    // below line is to create a geo point and we are getting
                    // geo point from firebase and setting to it.
                    GeoPoint geoPoint = value.getGeoPoint("geoPoint");

                    // getting latitude and longitude from geo point
                    // and setting it to our location.
                    LatLng location = new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude());

                    // adding marker to each location on google maps
                    mMap.addMarker(new MarkerOptions().position(location).title("Name"));

                    // below line is use to move camera.
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
                } else {
                    Toast.makeText(MapsActivity.this, "Error found is " + error, Toast.LENGTH_SHORT).show();
                }
            }
        });

        //Adding custom maps style over here
        //******** THIS PART OF CODE EXCLUSIVELY DESIGNED TO FETCH THE CUSTOM MAPS.JSON TEMPLATE**********
        enableMyLocation();

        try {
            // Customise the styling of the base map using a JSON object defined
            // in a raw resource file.
            boolean success = googleMap.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(
                            this, R.raw.mapstyle));
            if (!success) {
                Log.e("MapsActivity", "Style parsing failed.");
            }
            } catch (Resources. NotFoundException e) {
            Log.e("MapsActivity", "Can't find style. Error: ", e);
        }
        //******** MAP STYLING CODE ENDS OVER HERE **********

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        LatLng islamabad = new LatLng(33.68, 73.04);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Islamabad"));
        //moving the camera position to Islamabad.
        mMap.moveCamera(CameraUpdateFactory.newLatLng(islamabad));

    }

    //Getting the Users current Location

    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {
            ActivityCompat.requestPermissions(this, new String[]
                            {Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_LOCATION_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        // Check if location permissions are granted and if so enable the
        // location data layer.
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_LOCATION_PERMISSION:
                if (grantResults.length > 0
                        && grantResults[0]
                        == PackageManager.PERMISSION_GRANTED) {
                    enableMyLocation();
                    break;
                }
        }
    }
}

Body:
Instead of implementing a SearchView, add the places API from google in your grade file as follows:

implementation 'com.google.android.libraries.places:places:2.3.0'

and use AutocompleteSupportFragment as follows:

try {
                    if (!Places.isInitialized()) {
                        Places.initialize(getActivity().getApplicationContext(), GlobalVariables.google_api_key);
                    }
  // Initialize the AutocompleteSupportFragment.
    AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment) getChildFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

        autocompleteFragment.getView().setBackground(ContextCompat.getDrawable(getContext(), R.drawable.bginfo_whit));
        autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG));
        autocompleteFragment.setCountry("ET");
        autocompleteFragment.setMenuVisibility(false);
        autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
             @Override
                public void onPlaceSelected(Place place) {
                    // TODO: Get info about the selected place.
                    LatLng newLatLng = place.getLatLng();
                     mMap.moveCamera(CameraUpdateFactory.newLatLng(newLatLng));
                     mMap.animateCamera(CameraUpdateFactory.zoomTo(17));
                    }

            @Override
                 public void onError(Status status) {
                    // TODO: Handle the error.
                     //Log.i(TAG, "An error occurred: " + status);
                    }

                 });
                }
                catch (Exception e)
                {}


问:
iPhone: IB, switching between iPhone and iPad
I have a project. When I choose some xib file, iPhone simulator shows in IB. Is there any whey to change it to iPad simulator ? Thanks in advance...</p>

答:
iPhone and iPad user interface are defined in different XIB files. When you create a new XIB, Xcode asks you whether it's for the iPad or iPhone/iPod touch.

Go on, create a new XIB (choose a template containing only a window or view) and you'll see.

(Of course, there are many more steps to perform before it actually works. Read articles about universal apps to know more.)


问:
Slick slider extra options as data attribute
From documentation the data attribute work like this

```<code>data-slick='{"dots": true}'
</code>```

For this jquery version

```<code>$('.one-time').slick({
  dots: true,
});
</code>```

However for more complex settings how does data attribute should be written?Say

```<code>        $('.center').slick({
         dots: true,
         responsive: [
        {
          breakpoint: 768,
          settings: {
            arrows: false,
            centerMode: true,
            centerPadding: '40px',
            slidesToShow: 3
          }
        },
        {
          breakpoint: 480,
          settings: {
            arrows: false,
            centerMode: true,
            centerPadding: '40px',
            slidesToShow: 1
          }
        }
      ]
    });
</code>```

答: In addition to the above comment by Fabian, no trailing commas are allowed in the json.</p>

Body:
From documentation the data attribute work like this

data-slick='{"dots": true}'

For this jquery version

$('.one-time').slick({
  dots: true,
});

However for more complex settings how does data attribute should be written?Say

        $('.center').slick({
         dots: true,
         responsive: [
        {
          breakpoint: 768,
          settings: {
            arrows: false,
            centerMode: true,
            centerPadding: '40px',
            slidesToShow: 3
          }
        },
        {
          breakpoint: 480,
          settings: {
            arrows: false,
            centerMode: true,
            centerPadding: '40px',
            slidesToShow: 1
          }
        }
      ]
    });


问:
Making checkpoints in unity
I am trying to make a script where the player is repawned after hitting a checkpoint and dying subsequently. However, currently nothing happens when my player collides with an object marked as collision, so I could do with some help as to get the script working.

```<code>{
    [SerializeField] private Transform player;
    [SerializeField] private Transform respawn1;
    [SerializeField] private Transform respawn2;
    [SerializeField] private Transform respawn3;
    private int checkpointCount = 1;

    private void OnTriggerEnter(Collider other)
    {
        Rigidbody RB = player.GetComponent<Rigidbody>();
        if (other.gameObject.tag == "Respawn")
        {
            BoxCollider BC = other.gameObject.GetComponent<BoxCollider>();
            BC.enabled = false;
            checkpointCount++;

        }
        if (other.gameObject.tag == "Collision")
        {
            if (checkpointCount == 2)
            {

                player.transform.position = respawn2.transform.position;

            }
            else if (checkpointCount == 3)
            {
                player.transform.position = respawn3.transform.position;
            }
            else

                player.transform.position = respawn1.transform.position;
        }

</code>```

Thanks.

答:
Do you have the colliders in the checkpoints as a trigger ?
You need to check on trigger so you can use OnTriggerEnter otherwise you use OnCollisionEnter

Title: Making checkpoints in unity

Body:
I am trying to make a script where the player is repawned after hitting a checkpoint and dying subsequently. However, currently nothing happens when my player collides with an object marked as collision, so I could do with some help as to get the script working.

{
    [SerializeField] private Transform player;
    [SerializeField] private Transform respawn1;
    [SerializeField] private Transform respawn2;
    [SerializeField] private Transform respawn3;
    private int checkpointCount = 1;

    private void OnTriggerEnter(Collider other)
    {
        Rigidbody RB = player.GetComponent<Rigidbody>();
        if (other.gameObject.tag == "Respawn")
        {
            BoxCollider BC = other.gameObject.GetComponent<BoxCollider>();
            BC.enabled = false;
            checkpointCount++;

        }
        if (other.gameObject.tag == "Collision")
        {
            if (checkpointCount == 2)
            {

                player.transform.position = respawn2.transform.position;

            }
            else if (checkpointCount == 3)
            {
                player.transform.position = respawn3.transform.position;
            }
            else

                player.transform.position = respawn1.transform.position;
        }

Thanks.


问:
Is it possible to pass a Sass variable to Laravel/Blade/JS?
I'm trying to get a variable I use in Sass over to Laravel/Blade/JS so that I can use one variable defined in one place to maintain something across the various languages used to maintain the site.

Is it possible to pass a Sass variable to Laravel/Blade/JS so I can do this? Thanks.

答:
Here a kind of custom solution to export your Sass variables to a Js file.

First my Sass variables :

```<code>$bifurcation                : violet;
$simple                     : green;
$multiple                   : orange;
$crossing                   : yellow;
$common                     : brown;
</code>```

I put them into an unknown css property :

```<code>variable_to_export {
    start_export: unset;
    bifurcation: $bifurcation;
    simple: $simple;
    multiple: $multiple;
    crossing: $crossing;
    common: $common;
    end_export: unset;
}
</code>```

On my js file, i'm going to read the compiled scss file containing my 'variable_to_export'. This block of code is in a function that I can export to all my files that need it :

```<code>export function variables() {
    var variables = [];

    $.ajax({
        url: "/css/global.css",
        dataType: "text",
        success: function(css) {
            var position = css.indexOf('start_export');
            var position_end = css.indexOf('end_export');
            var clean = css.slice(position, position_end).replace(/ /g, '').replaceAll(';', '');
            var array_variables = clean.split(/\r?\n/);

            array_variables.forEach(function(element) {
                var split = element.split(':');
                if (split[0] != 'start_export' && split[0] != '') {
                    variables[split[0]] = split[1];
                }
            });
        }
    });

    return variables;
}
</code>```

At this stage we have an array containing the name of the css property as index, and the value of the Sass variable in my desired js files.

Result here

I think there are surely things to improve, the solution is a bit rooty but it works.

Body:
Here a kind of custom solution to export your Sass variables to a Js file.

First my Sass variables :

$bifurcation                : violet;
$simple                     : green;
$multiple                   : orange;
$crossing                   : yellow;
$common                     : brown;

I put them into an unknown css property :

variable_to_export {
    start_export: unset;
    bifurcation: $bifurcation;
    simple: $simple;
    multiple: $multiple;
    crossing: $crossing;
    common: $common;
    end_export: unset;
}

On my js file, i'm going to read the compiled scss file containing my 'variable_to_export'. This block of code is in a function that I can export to all my files that need it :

export function variables() {
    var variables = [];

    $.ajax({
        url: "/css/global.css",
        dataType: "text",
        success: function(css) {
            var position = css.indexOf('start_export');
            var position_end = css.indexOf('end_export');
            var clean = css.slice(position, position_end).replace(/ /g, '').replaceAll(';', '');
            var array_variables = clean.split(/\r?\n/);

            array_variables.forEach(function(element) {
                var split = element.split(':');
                if (split[0] != 'start_export' && split[0] != '') {
                    variables[split[0]] = split[1];
                }
            });
        }
    });

    return variables;
}

At this stage we have an array containing the name of the css property as index, and the value of the Sass variable in my desired js files.

Result here

I think there are surely things to improve, the solution is a bit rooty but it works.


问:
Python csv.DictReader. Read alter dictionary then output to file
I need to read in a pipe delimited file change some fields and output. It reads in fine and I am able to change the columns. The writer part writes the header but writerows doesn't write anything. How can I output the updated contents?</p>
```<code>csv.register_dialect('pipe',delimiter='|', quoting=csv,QUOTE_NONE)

with open('test.txt') as csvfile
    cfile=csv.DictReader(cfile,dialect='pipe')
    fieldnames=cfile.fieldnames
    for row in cfile:
        row['address']=scrubrow(row['address']

    with open('c.txt','w') as outfile:
        writer=csv.DictWriter(outfile,fieldnames=fieldnames,dialect='pipe')
        writer.writeheader()
        writer.writerows(cfile)

</code>```

答:
cfile is an empty iterator. And you discarded all but the last row, so doing row['address']=scrubrow(row['address'] didn't actually do anything.

The simple way to do this is to create a list and use that list:

```<code>csv.register_dialect('pipe',delimiter='|', quoting=csv,QUOTE_NONE)

with open('test.txt') as csvfile
    reader = csv.DictReader(cfile, dialect='pipe')
    fieldnames = cfile.fieldnames
    rows = []
    for row in reader:
        rows.append(scrubrow(row['address']))

    with open('c.txt','w') as outfile:
        writer = csv.DictWriter(outfile, fieldnames=fieldnames, dialect='pipe')
        writer.writeheader()
        writer.writerows(rows)
</code>```

But this will be inefficient because it will require O(N) space. Instead, keeping only a single row in memory at a time, you could do:

```<code>csv.register_dialect('pipe',delimiter='|', quoting=csv,QUOTE_NONE)

with open('test.txt') as csvfile, open('c.txt','w') as outfile:
    reader = csv.DictReader(cfile,dialect='pipe')

    fieldnames = reader.fieldnames
    writer = csv.DictWriter(outfile,fieldnames=fieldnames,dialect='pipe')

    writer.writeheader()
    for row in reader:
        writer.writerow(scrubrow(row['address']))

</code>```

Body:
I need to read in a pipe delimited file change some fields and output. It reads in fine and I am able to change the columns. The writer part writes the header but writerows doesn't write anything. How can I output the updated contents?

csv.register_dialect('pipe',delimiter='|', quoting=csv,QUOTE_NONE)

with open('test.txt') as csvfile
    cfile=csv.DictReader(cfile,dialect='pipe')
    fieldnames=cfile.fieldnames
    for row in cfile:
        row['address']=scrubrow(row['address']

    with open('c.txt','w') as outfile:
        writer=csv.DictWriter(outfile,fieldnames=fieldnames,dialect='pipe')
        writer.writeheader()
        writer.writerows(cfile)

Body:
cfile is an empty iterator. And you discarded all but the last row, so doing row['address']=scrubrow(row['address'] didn't actually do anything.

The simple way to do this is to create a list and use that list:

csv.register_dialect('pipe',delimiter='|', quoting=csv,QUOTE_NONE)

with open('test.txt') as csvfile
    reader = csv.DictReader(cfile, dialect='pipe')
    fieldnames = cfile.fieldnames
    rows = []
    for row in reader:
        rows.append(scrubrow(row['address']))

    with open('c.txt','w') as outfile:
        writer = csv.DictWriter(outfile, fieldnames=fieldnames, dialect='pipe')
        writer.writeheader()
        writer.writerows(rows)

But this will be inefficient because it will require O(N) space. Instead, keeping only a single row in memory at a time, you could do:

csv.register_dialect('pipe',delimiter='|', quoting=csv,QUOTE_NONE)

with open('test.txt') as csvfile, open('c.txt','w') as outfile:
    reader = csv.DictReader(cfile,dialect='pipe')

    fieldnames = reader.fieldnames
    writer = csv.DictWriter(outfile,fieldnames=fieldnames,dialect='pipe')

    writer.writeheader()
    for row in reader:
        writer.writerow(scrubrow(row['address']))


问:
UIDatePicker Month/Year Blank On Load
I have an almost working datepicker with the following settings:

Preferred Style: Automatic

Mode: Date

Locale: Default

Date: Current Date

My problem is the current month and year name do not appear on load. Instead, the right arrow icon is in its place, and the month and year name only show after I've selected a day from the calendar.

I've tried .setDate on the datePicker in viewDidLayoutSubviews() as a try, but still seeing the same result. Any guidance would be appreciated as I could not find any existing solution online.

I created the datePicker through storyboard, but here is the remaining code as it pertains to the datePicker onLoad:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    calendarDatePicker.preferredDatePickerStyle = .inline
    calendarDatePicker.overrideUserInterfaceStyle = .dark
    calendarDatePicker.date = //current date
    calendarDatePickerContainerView.layer.cornerRadius = 8
    calendarDatePickerContainerView.layer.masksToBounds = true
    calendarDatePickerContainerViewBottomConstraint.constant -= self.view.bounds.size.height
    self.view.layoutIfNeeded()
}
</code>```

```<code>override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    guard let current = currentDate else { return }
    calendarDatePicker.setDate(current, animated: true)
}
</code>```

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    DispatchQueue.main.async {
        UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: .curveEaseIn, animations: {
            self.calendarDatePickerContainerViewBottomConstraint.constant = 0
            self.view.layoutIfNeeded()
        }, completion: nil)
    }
}
</code>```

答:
Okay, so something about animating the containerView from the bottom up was screwing with the display.

Removing viewDidLayoutSubviews and capturing .setDate under a DispatchQueue.main.asyncAfter in viewWillAppear made things finally display correctly for me.

Title: UIDatePicker Month/Year Blank On Load

Body:
I have an almost working datepicker with the following settings:

Preferred Style: Automatic

Mode: Date

Locale: Default

Date: Current Date

My problem is the current month and year name do not appear on load. Instead, the right arrow icon is in its place, and the month and year name only show after I've selected a day from the calendar.

I've tried .setDate on the datePicker in viewDidLayoutSubviews() as a try, but still seeing the same result. Any guidance would be appreciated as I could not find any existing solution online.

I created the datePicker through storyboard, but here is the remaining code as it pertains to the datePicker onLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    calendarDatePicker.preferredDatePickerStyle = .inline
    calendarDatePicker.overrideUserInterfaceStyle = .dark
    calendarDatePicker.date = //current date
    calendarDatePickerContainerView.layer.cornerRadius = 8
    calendarDatePickerContainerView.layer.masksToBounds = true
    calendarDatePickerContainerViewBottomConstraint.constant -= self.view.bounds.size.height
    self.view.layoutIfNeeded()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    guard let current = currentDate else { return }
    calendarDatePicker.setDate(current, animated: true)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    DispatchQueue.main.async {
        UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: .curveEaseIn, animations: {
            self.calendarDatePickerContainerViewBottomConstraint.constant = 0
            self.view.layoutIfNeeded()
        }, completion: nil)
    }
}


问:
Get Group sum not using group.Sum() in linq
The following query works, but I want to get the same result without using grp.Sum(). Can we do it?</p>
```<code>from item in (await VehicleReplaceCostDataAsync())
                group item by (item.type, item.size, item.ADA, item.eseq) into grp
                orderby (grp.Key.eseq, grp.Key.size, grp.Key.ADA)
                select new VehicleReplacementCost
                {
                    type = grp.Key.type,
                    size = grp.Key.size,
                    ADA = grp.Key.ADA,
                    count = grp.Sum(x => x.count),
                    cost = grp.Sum(x => x.cost),
                    Fcount = grp.Sum(x => x.Fcount),
                    Fcost = grp.Sum(x => x.Fcost),
                    eseq = grp.Key.eseq,
                }).ToList();
</code>```

答:
Perhaps by using .Aggregate()? [docs]

```<code>count = grp.Aggregate(0, (a, b) => a + b.count)
</code>```

Body:
The following query works, but I want to get the same result without using grp.Sum(). Can we do it?

from item in (await VehicleReplaceCostDataAsync())
                group item by (item.type, item.size, item.ADA, item.eseq) into grp
                orderby (grp.Key.eseq, grp.Key.size, grp.Key.ADA)
                select new VehicleReplacementCost
                {
                    type = grp.Key.type,
                    size = grp.Key.size,
                    ADA = grp.Key.ADA,
                    count = grp.Sum(x => x.count),
                    cost = grp.Sum(x => x.cost),
                    Fcount = grp.Sum(x => x.Fcount),
                    Fcost = grp.Sum(x => x.Fcost),
                    eseq = grp.Key.eseq,
                }).ToList();

Body:
Perhaps by using .Aggregate()? [docs]

count = grp.Aggregate(0, (a, b) => a + b.count)


问:
Second  in JS not working "Uncaught TypeError: Cannot set properties of null (setting 'onclick')"
i wrote a JS code for my Website, which should show a modal and close it, if i click the "close" span. The first time, it worked perfectly. Here is the code:

```<code>var modal = document.getElementById("notifications");
var img = document.getElementById("shownotificationbar");
var span = document.getElementsByClassName("close")[0];

img.onclick = function() {
  modal.style.display = "block";
}

span.onclick = function() {
  modal.style.display = "none";
}
</code>```

But the second time, the close button just dont work and i get

"Uncaught TypeError: Cannot set properties of null (setting 'onclick')"

Here is the second code piece:

```<code>var menu = document.getElementById("startmenu");
var img = document.getElementById("showstartmenu");
var span = document.getElementById("closemenu");

img.onclick = function() {
  menu.style.display = "block";
}

span.onclick = function() {
  menu.style.display = "none";
}
</code>```

I think i can't use two spans, but what else should i do?
Thank you very much!

答:
The second time img is null, so you cannot set img.onclick. The reason it is null is probably that there is no element with id showstartmenu, so when you are trying to get it (document.getElementById("showstartmenu")), you are getting null instead.

Edit:

Sorry, it could also be that span is null, for the same reason. I missed that one.

Title: Second <span> in JS not working "Uncaught TypeError: Cannot set properties of null (setting 'onclick')"

Body:
i wrote a JS code for my Website, which should show a modal and close it, if i click the "close" span. The first time, it worked perfectly. Here is the code:

var modal = document.getElementById("notifications");
var img = document.getElementById("shownotificationbar");
var span = document.getElementsByClassName("close")[0];

img.onclick = function() {
  modal.style.display = "block";
}

span.onclick = function() {
  modal.style.display = "none";
}

But the second time, the close button just dont work and i get

"Uncaught TypeError: Cannot set properties of null (setting 'onclick')"

Here is the second code piece:

var menu = document.getElementById("startmenu");
var img = document.getElementById("showstartmenu");
var span = document.getElementById("closemenu");

img.onclick = function() {
  menu.style.display = "block";
}

span.onclick = function() {
  menu.style.display = "none";
}

I think i can't use two spans, but what else should i do?
Thank you very much!


问:
Is it correct to keep the ids of different related tables in the database?
I have two different entities for employees and managers, but they have one common attribute, in the announcements table is it right even if I did not send any announcement to the employee or manager?

答:
Yes it is,it is actually quite common.

What you got is a bridge table between employee and manager, and you added necessary column to the table, which enhance the bridge table.

If there is no relation ship between employee and manager, if you doun't sed announcement, then ther is no entry in the bridge table, you can chekc i the table if an employee never got such an announcement or how many he got


问:
How to indent/format a selection of code in Visual Studio Code?
I want to indent a specific section of code in Visual Studio Code.

I read How do you format code in Visual Studio Code? that gives shortcuts to indent the whole code, but it doesn't work when selecting a specific section of code.

I tried Ctrl + Shift + F after selecting some line in my code, but the whole file is indented. I'm on Windows with Visual Studio Code Insider 1.8.0. How can I do it?

答: Crtl + Alt + F can also formate (windows)


问:
How can I null-check this?
```<code>FutureBuilder(
  future: GetLiter(),
  builder: (context, snapshot) => Text(
    "Estimated bill \n\n\n" + snapshot.data * 0.00556 + " $",
    textAlign: TextAlign.center,
    style: TextStyle(fontSize: 20),
  ), // Text
), // FutureBuilder
</code>```

I have "An expression whose value can be 'null' must be null-checked before it can be dereferenced." error in snapshot.data. How can I null-check this?

GetLiter() func is here =>

```<code>Future<Object?> GetLiter() async {
  FirebaseDatabase database = FirebaseDatabase.instance;

  DatabaseReference ref = FirebaseDatabase.instance.ref("Liter");

  DatabaseEvent event = await ref.once();

  // print(event.snapshot.value);
  return event.snapshot.value;
}
</code>```

答:
FutureBuilders do not wait for the future to complete before they build and therefore snapshot.data could be null. You need to check this before you build or else the build will fail. Try this out:

import 'package:flutter/material.dart';

FutureBuilder(
  future: GetLiter(),
  builder: (context, snapshot) {
    if(snapshot.hasError){
      print(snapshot.error);
    }
    if(snapshot.hasData){
      return Text(
        "Estimated bill \n\n\n" + snapshot.data! * 0.00556 + " $",
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 20),
      ),
    } else {
      return CircularProgressIndicator();
    }
  }
),
```

Title: How can I null-check this?

Body:
FutureBuilder(
  future: GetLiter(),
  builder: (context, snapshot) => Text(
    "Estimated bill \n\n\n" + snapshot.data * 0.00556 + " $",
    textAlign: TextAlign.center,
    style: TextStyle(fontSize: 20),
  ), // Text
), // FutureBuilder

I have "An expression whose value can be 'null' must be null-checked before it can be dereferenced." error in snapshot.data. How can I null-check this?

GetLiter() func is here =>

Future<Object?> GetLiter() async {
  FirebaseDatabase database = FirebaseDatabase.instance;

  DatabaseReference ref = FirebaseDatabase.instance.ref("Liter");

  DatabaseEvent event = await ref.once();

  // print(event.snapshot.value);
  return event.snapshot.value;
}


问:
How do I use git to checkout just the files and their parent folders that have a given file extension?
We would be using this inside an Ant build script running under TeamCity.</p>

答:
(By "checkout" I assume that you mean "clone" in git terminology - i.e. you currently don't have a copy of the repository, and need to get some files from a remote repository.)

The short answer is that you can't.

You can, with some restrictions, do shallow clones in git (only getting the last few versions), but you can't easily do narrow clones (grabbing only some parts of the repository, such as one subdirectory, or only files that match particular criteria).

In a way, this is actually a feature of git as a distributed version control system: when you've cloned a repository you know that you've got the complete history, all the branches, and everything you need to work on the code completely standalone.

There are, of course, various ways around this, for example:

you could use git archive --remote=<repo> to fetch a tar archive of the remote repository, and pipe that to tar -x --wildcards --no-anchored '*.whatever'

just clone the complete repository somewhere else locally, and have your build script update it and copy over just the files you want

etc. etc.


问:
how to fail an excutionStep in synthetics canary
I am trying to figure out how I can fail a step in the canary script without failing the whole execution.

```<code>// code inside the handler

await synthetics.executeStep('My Step', async () => {
  // have some code here...
});

await synthetics.executeStep('My Other step', async () => {
  // I want to fail this step and only this one
});
</code>```

Using this syntax crashes the canary completely without any run results

```<code>await synthetics.executeStep('My Other step', async () => {
  // some code here...
  throw 'An Error Occured';

},
// @ts-ignore
    {
        continueOnStepFailure: true,
        screenshotOnStepFailure: true
    }
);

</code>```

and using synthetics.addExecutionError('error happened here') instead of the throw doesn't fail the whole canary (I still get results) but it fails its run result and shows that all the steps are passing.

What I want is to fail just a specific step and see that that step is ACTUALLY failing.

答:
In order to control the pass/fail of Synthetics canary, the validation function needs to return a Promise that's resolved/rejected. You're using an anonymous function for response validation, but the same concept applies.

```<code>const requestOptions = {
    'hostname': 'hostname.com',
    'path': '/api/v1/endpoint',
    'port': 443,
    'protocol': 'https:',
    'method': 'GET'
};

const validateResponse = async (res) => {
    return new Promise((resolve, reject) => {
        if (res.statusCode < 200 || res.statusCode > 299) {
            throw res.statusCode + ' ' + res.statusMessage;
        }

        let responseBody = '';
        res.on('data', (d) => {
            responseBody += d;
        });

        // validate the response body
        res.on('end', () => {
            const bodyJson = JSON.parse(responseBody);
            if (bodyJson.item == true) {
                log.info('Check Success!');
                return resolve();
            }
            log.error('item is false');
            reject('item is false');
        });
    });
};

await synthetics.executeHttpStep('Step Name', requestOptions, validateResponse);
</code>```

This sample code is derived from the 'Multi-step API canary' example in the AWS docs.

As you (and anyone who comes across this) might be able to tell, how to fail a synthetics step is not well documented. In the example AWS provides, you can see that they're returning a promise in their validation functions and then simply using throw within the promise to signal Step error when the HTTP response code is wrong, this is functionally the same as their code saying reject(res.statusCode + ' ' + res.statusMessage).

However, if you follow their pattern and simply put throw 'reason' in your res.on('end', ... function block then the throw method will cause the entire canary's execution to fail (due to scope).

The fix to this is to use reject('reason') to signal step failure. If you simply put reject() it will NOT signal failure and the step will still succeed.

Body:
I am trying to figure out how I can fail a step in the canary script without failing the whole execution.

// code inside the handler

await synthetics.executeStep('My Step', async () => {
  // have some code here...
});

await synthetics.executeStep('My Other step', async () => {
  // I want to fail this step and only this one
});

Using this syntax crashes the canary completely without any run results

await synthetics.executeStep('My Other step', async () => {
  // some code here...
  throw 'An Error Occured';

},
// @ts-ignore
    {
        continueOnStepFailure: true,
        screenshotOnStepFailure: true
    }
);

and using synthetics.addExecutionError('error happened here') instead of the throw doesn't fail the whole canary (I still get results) but it fails its run result and shows that all the steps are passing.

What I want is to fail just a specific step and see that that step is ACTUALLY failing.

Body:
In order to control the pass/fail of Synthetics canary, the validation function needs to return a Promise that's resolved/rejected. You're using an anonymous function for response validation, but the same concept applies.

const requestOptions = {
    'hostname': 'hostname.com',
    'path': '/api/v1/endpoint',
    'port': 443,
    'protocol': 'https:',
    'method': 'GET'
};

const validateResponse = async (res) => {
    return new Promise((resolve, reject) => {
        if (res.statusCode < 200 || res.statusCode > 299) {
            throw res.statusCode + ' ' + res.statusMessage;
        }

        let responseBody = '';
        res.on('data', (d) => {
            responseBody += d;
        });

        // validate the response body
        res.on('end', () => {
            const bodyJson = JSON.parse(responseBody);
            if (bodyJson.item == true) {
                log.info('Check Success!');
                return resolve();
            }
            log.error('item is false');
            reject('item is false');
        });
    });
};

await synthetics.executeHttpStep('Step Name', requestOptions, validateResponse);

This sample code is derived from the 'Multi-step API canary' example in the AWS docs.

As you (and anyone who comes across this) might be able to tell, how to fail a synthetics step is not well documented. In the example AWS provides, you can see that they're returning a promise in their validation functions and then simply using throw within the promise to signal Step error when the HTTP response code is wrong, this is functionally the same as their code saying reject(res.statusCode + ' ' + res.statusMessage).

However, if you follow their pattern and simply put throw 'reason' in your res.on('end', ... function block then the throw method will cause the entire canary's execution to fail (due to scope).

The fix to this is to use reject('reason') to signal step failure. If you simply put reject() it will NOT signal failure and the step will still succeed.


问:
ExpressJS: How to prevent a user from posting/patching code inside req.body
I'm developing an API with expressJS. This API is a semi-weblog service, and clients can create, update and delete their posts and contents. I have a sec urity concern about implementing its post and patch routes.

If the user injects some JS code and sends it to API to store in Mongodb, could these codes affect our API? How can I prevent users from posting and patching requests with any code inside them?

I have found "xss-clean" middleware to sanitize the user input body, is it enough for this purpose?

Because it is very important to me to ensure that I am using the correct middleware to protect this API, I am asking this question.

答:
If the user injects some JS code and sends it to API to store in Mongodb, could these codes affect our API?

Generally speaking: It won't.

The code come into express as a message body. It gets parsed by your middleware into a data structure where it will appear as a string. You then put that string in an object of structured data that you pass through the Mongodb client API which sends it to the database with any escaping that is needed.

I have found "xss-clean" middleware to sanitize the user input body, is it enough for this purpose?

XSS is an attack in which data injected into an HTML document contains special characters which are treated as special characters in HTML.

e.g.

```<code><h1>{{ your_name }}</h1>
</code>```

Where your_name is data that contains .

This is generally dealt with by applying proper escaping to the data (at a very basic level that means replacing < with <).

XSS won't affect your API directly.

If your data is going to be taken out of the Mongodb store and injected into an HTML document, then XSS is a consideration.

xss-clean is a wrapper around xss-filters.

xss-filters looks (I've only glanced at it) like a good module and is designed to be used as an output filter (i.e. run just before you insert data into an HTML document).

xss-clean works as an input filter, which isn't a good approach. It makes your data HTML safe at the expense of making it not useful for any purpose other than HTML. You might want to use the data in an email, or generate a report in Excel format.

Body:
If the user injects some JS code and sends it to API to store in Mongodb, could these codes affect our API?

Generally speaking: It won't.

The code come into express as a message body. It gets parsed by your middleware into a data structure where it will appear as a string. You then put that string in an object of structured data that you pass through the Mongodb client API which sends it to the database with any escaping that is needed.

I have found "xss-clean" middleware to sanitize the user input body, is it enough for this purpose?

XSS is an attack in which data injected into an HTML document contains special characters which are treated as special characters in HTML.

e.g.

<h1>{{ your_name }}</h1>

Where your_name is data that contains <script>...</script>.

This is generally dealt with by applying proper escaping to the data (at a very basic level that means replacing < with &lt;).

XSS won't affect your API directly.

If your data is going to be taken out of the Mongodb store and injected into an HTML document, then XSS is a consideration.

xss-clean is a wrapper around xss-filters.

xss-filters looks (I've only glanced at it) like a good module and is designed to be used as an output filter (i.e. run just before you insert data into an HTML document).

xss-clean works as an input filter, which isn't a good approach. It makes your data HTML safe at the expense of making it not useful for any purpose other than HTML. You might want to use the data in an email, or generate a report in Excel format.


问:
How to add space beetween a pair of consecutive letters and not add space beetween two characters that are not both letters?
For example:
The string BINGO!
should be B I N G O!

I have already tried:

```<code>s = "BINGO!"
print(" ".join(s[::1]))
</code>```

答:
I'd use regex: re.sub(r'(?<=[a-zA-Z])(?=[a-zA-Z])', ' ', 'BINGO!')

This basically says, "for every empty string in 'BINGO!' that both follows a letter and precedes a letter, substitute a space."

Body:
For example:
The string BINGO!
should be B I N G O!

I have already tried:

s = "BINGO!"
print(" ".join(s[::1]))


问:
embeddedProvider.GetDirectoryContents returns 0 results
There are many posts on SO about how to access resource files. I'm very lost as to if one is preferred, or whether they are just different options.

.NET Core 3.1, Class Library

I created a new folder in my project, called ResourceFiles and added many files

I opened the csproj and added

```<code><EmbeddedResource Include="ResourceFiles/*" />
</code>```

And to consume this, I have

```<code>using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.FileProviders.Embedded;

namespace Core.Html
{
    internal static class Template
    {
        internal static string Get()
        {
            var embeddedProvider = new EmbeddedFileProvider(Assembly.GetExecutingAssembly());
            using (var reader = embeddedProvider.GetFileInfo("file.txt").CreateReadStream())
            {
                //stuff
            }
        }
     }
}
</code>```

This works great for a single file.

What I'd like to be able to do is return a collection of FileInfo because in the ResourceFiles directory, there are many files.

I was hoping to do the following

```<code>var allFiles = embeddedProvider.GetDirectoryContents("ResourceFiles");
</code>```

This always returns an empty list. I don't understand why. What am I doing wrong?

答: Looking at the source of EmbeddedFileProvider it only supports files in the root. If you supply anything other than "/" this method will fail.</p>

Body:
There are many posts on SO about how to access resource files. I'm very lost as to if one is preferred, or whether they are just different options.

.NET Core 3.1, Class Library

I created a new folder in my project, called ResourceFiles and added many files

I opened the csproj and added

<EmbeddedResource Include="ResourceFiles/*" />

And to consume this, I have

using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.FileProviders.Embedded;

namespace Core.Html
{
    internal static class Template
    {
        internal static string Get()
        {
            var embeddedProvider = new EmbeddedFileProvider(Assembly.GetExecutingAssembly());
            using (var reader = embeddedProvider.GetFileInfo("file.txt").CreateReadStream())
            {
                //stuff
            }
        }
     }
}

This works great for a single file.

What I'd like to be able to do is return a collection of FileInfo because in the ResourceFiles directory, there are many files.

I was hoping to do the following

var allFiles = embeddedProvider.GetDirectoryContents("ResourceFiles");

This always returns an empty list. I don't understand why. What am I doing wrong?


问:
How to save and reuse model in python
I have build a model and saved it using pickle library but I wanna use it again by changing the values of my input variables and for that I don't have any output.

Here is the code :

```<code># Save Model Using Pickle
import pandas
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
import pickle
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-
diabetes.data.csv"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = pandas.read_csv(url, names=names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
test_size = 0.33
seed = 7
X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size,
random_state=seed)
# Fit the model on training set
model = LogisticRegression()
model.fit(X_train, Y_train)
# save the model to disk
filename = 'finalized_model.sav'
pickle.dump(model, open(filename, 'wb'))

# some time later...

# load the model from disk
loaded_model = pickle.load(open(filename, 'rb'))
result = loaded_model.score(X_test, Y_test)
print(result)
</code>```

Now, I have only data for my X_test. I don't have any data point for my Y_test. In such case how I can use it again and pass only X_test and it gives me Y.
Please help!!

答:
This shall work:</p>
```<code>loaded_model.predict(X_test)
</code>```

Title: How to save and reuse model in python

Body:
I have build a model and saved it using pickle library but I wanna use it again by changing the values of my input variables and for that I don't have any output.

Here is the code :

# Save Model Using Pickle
import pandas
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
import pickle
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-
diabetes.data.csv"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = pandas.read_csv(url, names=names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
test_size = 0.33
seed = 7
X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size,
random_state=seed)
# Fit the model on training set
model = LogisticRegression()
model.fit(X_train, Y_train)
# save the model to disk
filename = 'finalized_model.sav'
pickle.dump(model, open(filename, 'wb'))

# some time later...

# load the model from disk
loaded_model = pickle.load(open(filename, 'rb'))
result = loaded_model.score(X_test, Y_test)
print(result)

Now, I have only data for my X_test. I don't have any data point for my Y_test. In such case how I can use it again and pass only X_test and it gives me Y.
Please help!!

Body:
This shall work:

loaded_model.predict(X_test)


问:
PHP and Objects - Extending a common object, which other objects inherit from
I have a base object (form_field_base) that is extended/inherited by other objects in the form of:

```<code>class form_field_base {
    // Lots of code
}
class form_field_text extends form_field_base {
    // Lots of code
}
class form_field_email extends form_field_text {
    // Extending the text object to update validation, and set input type="email"
}
class form_field_file extends form_field_base {
    // Lots of code, for example uploading files
}
</code>```

The "form_field_base" provides helper methods that all of the form field types use, for example a html() function calls the specific object (form_field_email::html_input) to get the  field, then put that in a string with the standard  tag, etc.

All of these objects are used by many projects.

However, this latest project I'm working on requires the "form_field_base" object to be customised to allow the setting of some help text, a feature that no other project requires, and if future projects do, it will probably be done differently.

So how should this have be organised?

Ideally I won't have a complete copy of "form_field_base", as that would cause code duplication.

And it does seem like quite a bit of overhead to have dummy intermediate objects:

```<code>class form_field_base_common {
    // Lots of code
}
class form_field_base extends form_field_base_common {
    // By default is empty
}

class form_field_text_common extends form_field_base {
    // Lots of code
}
class form_field_text extends form_field_text_common {
    // ...
}

class form_field_email_common extends form_field_text {
    // Extending the text object to update validation, and set input type="email"
}
class form_field_email extends form_field_email_common {
    // ...
}

class form_field_file_common extends form_field_base {
    // Lots of code, for example uploading files
}
class form_field_file extends form_field_file_common {
    // ...
}
</code>```

Taking that each one has it's own file, which is auto-loaded (either a from a project specific location, if it exists, or from a common folder that all projects can access)... that is already 8 files that need to be found, opened, parsed, etc, just for supporting a form.

Surly there has to be a better way?

答:
It depends what you want to do with the help text.  Perhaps, though you could do it like this:

1 - Create the help text object for the purposes you desire.
2 - Create an optional constructor parameter in your form_field_base class.  If set, it would be a private instance of the help text class.
3 - Inside your subclasses, check for the existence of the help text object.  If it is set, perform the additional action.

Perhaps this is not suitable for what you're trying to do, though.  Without being more sure, though, that's the best I could come up with!

Body:
I have a base object (form_field_base) that is extended/inherited by other objects in the form of:

class form_field_base {
    // Lots of code
}
class form_field_text extends form_field_base {
    // Lots of code
}
class form_field_email extends form_field_text {
    // Extending the text object to update validation, and set input type="email"
}
class form_field_file extends form_field_base {
    // Lots of code, for example uploading files
}

The "form_field_base" provides helper methods that all of the form field types use, for example a html() function calls the specific object (form_field_email::html_input) to get the  field, then put that in a string with the standard  tag, etc.

All of these objects are used by many projects.

However, this latest project I'm working on requires the "form_field_base" object to be customised to allow the setting of some help text, a feature that no other project requires, and if future projects do, it will probably be done differently.

So how should this have be organised?

Ideally I won't have a complete copy of "form_field_base", as that would cause code duplication.

And it does seem like quite a bit of overhead to have dummy intermediate objects:

class form_field_base_common {
    // Lots of code
}
class form_field_base extends form_field_base_common {
    // By default is empty
}

class form_field_text_common extends form_field_base {
    // Lots of code
}
class form_field_text extends form_field_text_common {
    // ...
}

class form_field_email_common extends form_field_text {
    // Extending the text object to update validation, and set input type="email"
}
class form_field_email extends form_field_email_common {
    // ...
}

class form_field_file_common extends form_field_base {
    // Lots of code, for example uploading files
}
class form_field_file extends form_field_file_common {
    // ...
}

Taking that each one has it's own file, which is auto-loaded (either a from a project specific location, if it exists, or from a common folder that all projects can access)... that is already 8 files that need to be found, opened, parsed, etc, just for supporting a form.

Surly there has to be a better way?


问:
SQL - STRING_SPLIT string position
I have a table with two columns of comma-separated strings. The way the data is formatted, the number of comma-separated items in both columns is equal, and the first value in colA is related to the first value in colB, and so on. (It's obviously not a very good data format, but it's what I'm working with.)

If I have the following row (PrimaryKeyID | column1 | column2):

```<code>1 | a,b,c | A,B,C
</code>```

then in this data format, a & 1 are logically related, b & 2, etc.

I want to use STRING_SPLIT to split these columns, but using it twice obviously crosses them with each other, resulting in a total of 9 rows.

```<code>1 | a | A
1 | b | A
1 | c | A
1 | a | B
1 | b | B
1 | c | B
1 | a | C
1 | b | C
1 | c | C
</code>```

What I want is just the 3 "logically-related" columns

```<code>1 | a | A
1 | b | B
1 | c | C
</code>```

However, STRING_SPLIT(myCol,',') doesn't appear to save the String Position anywhere.

I have done the following:

```<code>SELECT tbl.ID,
      t1.Column1Value,
      t2.Column2Value
FROM myTable tbl
INNER JOIN (
   SELECT t.ID,
       ss.value AS Column1Value,
       ROW_NUMBER() OVER (PARTITION BY t.ID ORDER BY t.ID) as StringOrder
   FROM myTable t
   CROSS APPLY STRING_SPLIT(t.column1,',') ss
) t1 ON tbl.ID = t1.ID
INNER JOIN (
   SELECT t.ID,
       ss.value AS Column2Value,
       ROW_NUMBER() OVER (PARTITION BY t.ID ORDER BY t.ID) as StringOrder
   FROM myTable t
   CROSS APPLY STRING_SPLIT(t.column2,',') ss
) t1 ON tbl.ID = t2.ID AND t1.StringOrder = t2.StringOrder
</code>```

This appears to work on my small test set, but in my opinion there is no reason to expect it to work guaranteed every time. The ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) is obviously a meaningless ordering, but it appears that, in absence of any real ordering, STRING_SPLIT is returning the values in the "default" order that they were already in. Is this "expected" behaviour? Can I count on this? Is there any other way of accomplishing what I'm attempting to do?

Thanks.

======================

EDIT

I got what I wanted (I think) with the following UDF. However it's pretty slow. Any suggestions?

```<code>CREATE FUNCTION fn.f_StringSplit(@string VARCHAR(MAX),@delimiter VARCHAR(1))
RETURNS @r TABLE
(
    Position INT,
    String VARCHAR(255)
)
AS
BEGIN

    DECLARE @current_position INT
    SET @current_position = 1

    WHILE CHARINDEX(@delimiter,@string) > 0 BEGIN

        INSERT INTO @r (Position,String) VALUES (@current_position, SUBSTRING(@string,1,CHARINDEX(@delimiter,@string) - 1))

        SET @current_position = @current_position + 1
        SET @string = SUBSTRING(@string,CHARINDEX(@delimiter,@string) + 1, LEN(@string) - CHARINDEX(@delimiter,@string))

    END

    --add the last one
    INSERT INTO @r (Position, String) VALUES(@current_position,@string)

    RETURN
END
</code>```

答:
Fortunately in newer SQL Server (Azure and 2022) an optional flag has been added to String_Split to include an "ordinal" column.  If you are using a newer version of SQL Server, this finally provides a solution that is logically correct rather than implementation specific.

New definition:

```<code>String_Split(string, separator [, enable_ordinal])
e.g. String_Split('1.2.3', '.', 1)
</code>```

Example:

```<code>with V as (select Value v, Ordinal n from String_Split('1.2.3', '.', 1))
    select
        (select v from V where n = 1) Major,
        (select v from V where n = 2) Minor,
        (select v from V where n = 3) Revision
</code>```

Returns:

```<code>Major Minor Revision
----- ----- ---------
1     2     3
</code>```

Title: SQL - STRING_SPLIT string position

Body:
I have a table with two columns of comma-separated strings. The way the data is formatted, the number of comma-separated items in both columns is equal, and the first value in colA is related to the first value in colB, and so on. (It's obviously not a very good data format, but it's what I'm working with.)

If I have the following row (PrimaryKeyID | column1 | column2):

1 | a,b,c | A,B,C

then in this data format, a & 1 are logically related, b & 2, etc.

I want to use STRING_SPLIT to split these columns, but using it twice obviously crosses them with each other, resulting in a total of 9 rows.

1 | a | A
1 | b | A
1 | c | A
1 | a | B
1 | b | B
1 | c | B
1 | a | C
1 | b | C
1 | c | C

What I want is just the 3 "logically-related" columns

1 | a | A
1 | b | B
1 | c | C

However, STRING_SPLIT(myCol,',') doesn't appear to save the String Position anywhere.

I have done the following:

SELECT tbl.ID,
      t1.Column1Value,
      t2.Column2Value
FROM myTable tbl
INNER JOIN (
   SELECT t.ID,
       ss.value AS Column1Value,
       ROW_NUMBER() OVER (PARTITION BY t.ID ORDER BY t.ID) as StringOrder
   FROM myTable t
   CROSS APPLY STRING_SPLIT(t.column1,',') ss
) t1 ON tbl.ID = t1.ID
INNER JOIN (
   SELECT t.ID,
       ss.value AS Column2Value,
       ROW_NUMBER() OVER (PARTITION BY t.ID ORDER BY t.ID) as StringOrder
   FROM myTable t
   CROSS APPLY STRING_SPLIT(t.column2,',') ss
) t1 ON tbl.ID = t2.ID AND t1.StringOrder = t2.StringOrder

This appears to work on my small test set, but in my opinion there is no reason to expect it to work guaranteed every time. The ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) is obviously a meaningless ordering, but it appears that, in absence of any real ordering, STRING_SPLIT is returning the values in the "default" order that they were already in. Is this "expected" behaviour? Can I count on this? Is there any other way of accomplishing what I'm attempting to do?

Thanks.

======================

EDIT

I got what I wanted (I think) with the following UDF. However it's pretty slow. Any suggestions?

CREATE FUNCTION fn.f_StringSplit(@string VARCHAR(MAX),@delimiter VARCHAR(1))
RETURNS @r TABLE
(
    Position INT,
    String VARCHAR(255)
)
AS
BEGIN

    DECLARE @current_position INT
    SET @current_position = 1

    WHILE CHARINDEX(@delimiter,@string) > 0 BEGIN

        INSERT INTO @r (Position,String) VALUES (@current_position, SUBSTRING(@string,1,CHARINDEX(@delimiter,@string) - 1))

        SET @current_position = @current_position + 1
        SET @string = SUBSTRING(@string,CHARINDEX(@delimiter,@string) + 1, LEN(@string) - CHARINDEX(@delimiter,@string))

    END

    --add the last one
    INSERT INTO @r (Position, String) VALUES(@current_position,@string)

    RETURN
END

Body:
Fortunately in newer SQL Server (Azure and 2022) an optional flag has been added to String_Split to include an "ordinal" column.  If you are using a newer version of SQL Server, this finally provides a solution that is logically correct rather than implementation specific.

New definition:

String_Split(string, separator [, enable_ordinal])
e.g. String_Split('1.2.3', '.', 1)

Example:

with V as (select Value v, Ordinal n from String_Split('1.2.3', '.', 1))
    select
        (select v from V where n = 1) Major,
        (select v from V where n = 2) Minor,
        (select v from V where n = 3) Revision

Returns:

Major Minor Revision
----- ----- ---------
1     2     3


问:
How are promises (and async) "asynchronous", exactly?
Every single example I read about it has code demonstrations that are synchronously executed, with the article writers pretending they're asynchronous.

No example I've seen yet says the code keeps running past the 'asynchronous' promise. If the code kept running while the promise was fulfilled, or the await was taking place, then it could be called asynchonous.

But if the main line of code stops for the promise/await response, then it's simply synchronous.

Can anyone explain this? I had the impression that code ran past the promise/sync function, rather than stopping and 'awaiting' the result to then continue the rest of the code identically to a normal synchronous execution operation.

答:
Promises register callbacks for further execution when they resolve:

console.log('Beginning');
const test = new Promise(resolve => setTimeout(resolve, 1000));
test.then(() => console.log('Resolved'));
console.log('End');```
</div>
</div>
</p>
<p>Now if you think this is synchronous code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(async function() {
  console.log('Beginning');
  const test = new Promise(resolve => setTimeout(resolve, 1000));
  await test;
  console.log('Resolved');
  console.log('End');
})();</code>```

Well it's not, it's actually an equivalent of:

console.log('Beginning');
const test = new Promise(resolve => setTimeout(resolve, 1000));
test.then(() => {
  console.log('Resolved');
  console.log('End');
});```

Conclusion: when you await a Promise you just use syntactic sugar. Really nice syntactic sugar that prevents callback hell:

The call stack unwinds and frees the event loop with async/await, just like it would with callbacks, making the event loop available for other code execution until the Promise resolves.

Body:
Promises register callbacks for further execution when they resolve:

console.log('Beginning');
const test = new Promise(resolve => setTimeout(resolve, 1000));
test.then(() => console.log('Resolved'));
console.log('End');

Now if you think this is synchronous code:

(async function() {
  console.log('Beginning');
  const test = new Promise(resolve => setTimeout(resolve, 1000));
  await test;
  console.log('Resolved');
  console.log('End');
})();

Well it's not, it's actually an equivalent of:

console.log('Beginning');
const test = new Promise(resolve => setTimeout(resolve, 1000));
test.then(() => {
  console.log('Resolved');
  console.log('End');
});

Conclusion: when you await a Promise you just use syntactic sugar. Really nice syntactic sugar that prevents callback hell:

The call stack unwinds and frees the event loop with async/await, just like it would with callbacks, making the event loop available for other code execution until the Promise resolves.


问:
Remove an element of a list by name
I'm working with a long named list and I'm trying to keep/remove elements that match a certain name, within a tidyverse context, similar to

```<code>dplyr::select(contains("pattern"))
</code>```

However, I'm having issues figuring it out.

```<code>library(tidyverse)

a_list <-
  list(a = "asdfg",
       b = "qwerty",
       c = "zxcvb")

a_list %>% pluck("a") # works
a_list %>% pluck(contains("a")) #does not work

a_list[2:3] # this is what I want
a_list %>% pluck(-"a") # but this does not work
</code>```

答:
Same as Parisa's answer, just fits better into tidyverse pipe chains:

```<code>library(magrittr)

a_list <-
    list(a = "asdfg",
         b = "qwerty",
         c = "zxcvb")

a_list %>%
magrittr::inset(c('a', 'c'), NULL)
</code>```

Another alternative notation:

```<code>a_list %>%
`[<-`(c('a', 'b'), NULL)
</code>```

Title: Remove an element of a list by name

Body:
I'm working with a long named list and I'm trying to keep/remove elements that match a certain name, within a tidyverse context, similar to

dplyr::select(contains("pattern"))

However, I'm having issues figuring it out.

library(tidyverse)

a_list <-
  list(a = "asdfg",
       b = "qwerty",
       c = "zxcvb")

a_list %>% pluck("a") # works
a_list %>% pluck(contains("a")) #does not work

a_list[2:3] # this is what I want
a_list %>% pluck(-"a") # but this does not work

Body:
Same as Parisa's answer, just fits better into tidyverse pipe chains:

library(magrittr)

a_list <-
    list(a = "asdfg",
         b = "qwerty",
         c = "zxcvb")

a_list %>%
magrittr::inset(c('a', 'c'), NULL)

Another alternative notation:

a_list %>%
`[<-`(c('a', 'b'), NULL)


问:
can I forward same animationController again after AnimationStatus.completed
I want to make same animationController forward when the animation status is completed, and setState to update value which is inside animation tween, so the second animationController forward will achieve different animation, is that possible? thank you!</p>
```<code>GestureDetector(

        onTap: () {
          if (firstController.status == AnimationStatus.dismissed) {
            firstController.forward();
          } else if (firstController.status == AnimationStatus.completed) {
            setState(() {

              double firstOpacity = 1.0;  //new value
              double secondOpacity = 0.7;//new value
              double thirdOpacity = 0.4;//new value
            });
            firstController.forward();  // now it does not work
          }
        },
        child: Center(
          child: Container(
            child: AnimatedBuilder(
              animation: firstController,
              builder: _buildAnimation,
            ),
          ),
        ),
      ),
</code>```

答:
I hope you will get an idea from these links and code.</p>
```<code>  late Animation<double> _animation;
  late AnimationController _animationController;
  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
        vsync: this,
        duration: const Duration(milliseconds: 1500),
        reverseDuration: const Duration(milliseconds: 1500))
      ..forward();
    _animationController.addListener(() {
      if (_animationController.isCompleted) {
        _animationController.reverse();
      } else if (_animationController.isDismissed) {
        _animationController.forward();
      }
      setState(() {});
    });
    _animation =
        CurvedAnimation(parent: _animationController, curve: Curves.easeInOut);
    _animation = Tween(begin: -.6, end: .4).animate(_animation);
  }
</code>```

Body:
I want to make same animationController forward when the animation status is completed, and setState to update value which is inside animation tween, so the second animationController forward will achieve different animation, is that possible? thank you!

GestureDetector(

        onTap: () {
          if (firstController.status == AnimationStatus.dismissed) {
            firstController.forward();
          } else if (firstController.status == AnimationStatus.completed) {
            setState(() {

              double firstOpacity = 1.0;  //new value
              double secondOpacity = 0.7;//new value
              double thirdOpacity = 0.4;//new value
            });
            firstController.forward();  // now it does not work
          }
        },
        child: Center(
          child: Container(
            child: AnimatedBuilder(
              animation: firstController,
              builder: _buildAnimation,
            ),
          ),
        ),
      ),

Body:
I hope you will get an idea from these links and code.

  late Animation<double> _animation;
  late AnimationController _animationController;
  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
        vsync: this,
        duration: const Duration(milliseconds: 1500),
        reverseDuration: const Duration(milliseconds: 1500))
      ..forward();
    _animationController.addListener(() {
      if (_animationController.isCompleted) {
        _animationController.reverse();
      } else if (_animationController.isDismissed) {
        _animationController.forward();
      }
      setState(() {});
    });
    _animation =
        CurvedAnimation(parent: _animationController, curve: Curves.easeInOut);
    _animation = Tween(begin: -.6, end: .4).animate(_animation);
  }