问:
Relationship between PlatformTarget and RuntimeIdentifier in .NET 5
I'm confused about the relationship between RuntimeIdentifier and PlatformTarget in .NET 5.
My .NET 5 C# project runs and publishes fine, but PlatformTarget is 'AnyCPU' and RuntimeIdentifier is 'win-x64'.

From Microsoft's documentation, RuntimeIdentifier is "used to identify target platforms where the application runs".
https://learn.microsoft.com/en-us/dotnet/core/rid-catalog
Isn't this what 'PlatformTarget' is supposed to do?

I tried using RuntimeIdentifers (plural) which I've seen before (perhaps .NET Core 3?), but the project doesn't compile with this:

```<code><RuntimeIdentifiers>win-x64;win-x86</RuntimeIdentifiers>
</code>```

From my current project file:

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net5.0-windows</TargetFramework>
    <PublishSingleFile>true</PublishSingleFile>
    <SelfContained>true</SelfContained>
    <RuntimeIdentifier>win-x64</RuntimeIdentifier>   -> RuntimeIdentifier is required since SelfContained is 'true'
    ...
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    ...
    <PlatformTarget>AnyCPU</PlatformTarget>
  </PropertyGroup>
  ...
</Project>
</code>```

答:
It's true that the pile of properties is difficult to understand (Platform, Platforms, PlatformTarget, TargetFramework (Moniker), and RuntimeIdentifier). Here is my current take on the properties - keep in mind that I have still have questions because of the results of my experiments).

Platform, Platforms, and PlatformTarget: These properties are kind of synonyms (Platforms plural is required to hold multiple platform specifiers) and refer to the bitness/CPU architectures such as AnyCPU, x86, x64, and Arm. I always think "hardware" for this property.

TargetFramework: This specifies a NET Framework API version that the app is intended to run on (net48, net5.0, wp (windows phone), netcore, netcoreapp2.1, etc). Some of these are cross-platform (cross-hardware?).

RuntimeIdentifier: The runtime specifier is the cross-platform glue part of the stack and sits here in the abstraction level stack: app->framework->runtime->platform. If your library was configured for both x86 and x64, msbuild publishes the variations to bin/debug/framework/win-x86/ and bin/debug/framework/win-x64/ (so that win-x86 and win-64 and other runtimes are siblings in the output folder tree).

You must publish/build your project once (with different property values) for each runtime that you use.

To the original question, you can see that AnyCPU is a platform specifier and RIDs are runtime identifiers. The RID monikers often include x86/x64 in their names for communication convenience, but those strings do not specify the platform. Only the Platform specifier can specifier the platform.

In operation, you can specify Platform AnyCPU for building the app (indicating the app binary is appropriate for x86, x64, arm, etc., and then use a specific runtime in the publication operation (which will assign the 32/64 bitness etc. to the published binary).

My NET 5 project files require the definition of both a Platform and a TargetFramework if no MSBuild override arguments are provided. MSBuild assumes win-x64 for the runtime on my projects that define Platform=AnyCPU and TargetFramework=net5.0-windows7.0.

It's worth saying that MSBuild can get its properties from three places: the MSBuild project file; the Visual Studio dialog sheets (probably override the project file values; and the MSBuild command line (override the project file values).

Body:
I'm confused about the relationship between RuntimeIdentifier and PlatformTarget in .NET 5.
My .NET 5 C# project runs and publishes fine, but PlatformTarget is 'AnyCPU' and RuntimeIdentifier is 'win-x64'.

From Microsoft's documentation, RuntimeIdentifier is "used to identify target platforms where the application runs".
https://learn.microsoft.com/en-us/dotnet/core/rid-catalog
Isn't this what 'PlatformTarget' is supposed to do?

I tried using RuntimeIdentifers (plural) which I've seen before (perhaps .NET Core 3?), but the project doesn't compile with this:

<RuntimeIdentifiers>win-x64;win-x86</RuntimeIdentifiers>

From my current project file:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net5.0-windows</TargetFramework>
    <PublishSingleFile>true</PublishSingleFile>
    <SelfContained>true</SelfContained>
    <RuntimeIdentifier>win-x64</RuntimeIdentifier>   -> RuntimeIdentifier is required since SelfContained is 'true'
    ...
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    ...
    <PlatformTarget>AnyCPU</PlatformTarget>
  </PropertyGroup>
  ...
</Project>


来源: stackexchange

问:
Error response from daemon: open \\.\pipe\docker_engine_linux: The system cannot find the file specified
While I am trying to start with docker on my windows 10 machine it is returning the following error.

ERROR: open \.\pipe\docker_engine_linux: The system cannot find the file specified.

I found when I logon to my computer, the hyper VM could not run docker virtual machine automatically though my docker desktop is running. Once I start docker virtual machine on hyper VM and restart docker once again, it works okay. But this is not a permanent solution. Could I get some help please?

答: to solve this problem make sure you install one of the linux distribution like alpine or ubunto and that step alot of youtube vedio  tutorial miss nowaday in 2022 and by the way this step is menthoned in the https://learn.microsoft.com/en-us/windows/wsl/install-manual and i mean here the step number 6 in the manual installation of windows subsystem for linux as short wsl => https://learn.microsoft.com/en-us/windows/wsl/install-manual</p>

ContentLicense: CC BY-SA 4.0


问:
how set the windows clock using c++
I'm trying set the windows system clock using C++.
I'm trying with the following code(not working):

```<code>#include "stdafx.h"
#include "iostream"
#include "windows.h"
using namespace std;

int _tmain(int argc, _TCHAR* argv[]) {

    SYSTEMTIME st;
    st.wDay = 1;
    st.wMonth = 5;
    st.wYear = 2011;
    st.wHour = 12;
    st.wMinute = 15;
    bool result = SetLocalTime(&st);
    cout << result;
    return 0;
}
</code>```

Can someone point out my error? Thanks in advance.

答: st is incompletely initialized and contains invalid values.   Initialize it fully and the code works.  If you had called GetLastError(), it would have clued you in right away because it was returning 87, which is ERROR_INVALID_PARAMETER.  The day of week, seconds and milliseconds fields undoubtedly contain invalid values.</p>

ContentLicense: CC BY-SA 3.0

Title: how set the windows clock using c++

Body:
I'm trying set the windows system clock using C++.
I'm trying with the following code(not working):

#include "stdafx.h"
#include "iostream"
#include "windows.h"
using namespace std;

int _tmain(int argc, _TCHAR* argv[]) {

    SYSTEMTIME st;
    st.wDay = 1;
    st.wMonth = 5;
    st.wYear = 2011;
    st.wHour = 12;
    st.wMinute = 15;
    bool result = SetLocalTime(&st);
    cout << result;
    return 0;
}

Can someone point out my error? Thanks in advance.


问:
How do you call an instance with one parameter?
```<code>public void remove(String name, int population, double area, String continent) {
    /* Make a new country object for removing */
    Country removeCountry = new Country(name, population, area, continent);

    /* Linear Search for the instance we want to remove */
    for (int i = 0; i < size; i++) {
        if (removeCountry.equals(catalogue[i])) {
            catalogue[i] = catalogue[size - 1];
            catalogue[size - 1] = null;
            size--;
        }
    }
}
</code>```

Okay so this is in a different class and I want to replace line 1 with,

```<code>public void remove(String name)
</code>```

but I can't because on the third line, I have to replace population and area with a value, for the continent, I could just replace it with "" and it would work.

```<code>Country removeCountry = new Country(name, [value], [value], "");
</code>```

In the main class, I want to be able to input this code,

```<code>myCountry.remove("Canada");
</code>```

So basically, I want to somehow override my primitive type parameters by I don't know how.

答:
Java allows for method overloading, unlike some other programming languages. This essentially means you can write this into your code:

public void remove(String name, int population,
            double area, String continent) {

    // your code goes here

}

// This will have a different method signature
// and will allow you to use remove("Canada")
// on its own.
public void remove(String name) {

    remove(name, 0, 0.0, "");

}
```

Note that for this to work properly, we would have to assume that .equals() ignores the population, area, and continent fields. If it does use these fields, you would need a way to determine the fields programmatically, perhaps by using a country dictionary.

Body:
public void remove(String name, int population, double area, String continent) {
    /* Make a new country object for removing */
    Country removeCountry = new Country(name, population, area, continent);

    /* Linear Search for the instance we want to remove */
    for (int i = 0; i < size; i++) {
        if (removeCountry.equals(catalogue[i])) {
            catalogue[i] = catalogue[size - 1];
            catalogue[size - 1] = null;
            size--;
        }
    }
}

Okay so this is in a different class and I want to replace line 1 with,

public void remove(String name)

but I can't because on the third line, I have to replace population and area with a value, for the continent, I could just replace it with "" and it would work.

Country removeCountry = new Country(name, [value], [value], "");

In the main class, I want to be able to input this code,

myCountry.remove("Canada");

So basically, I want to somehow override my primitive type parameters by I don't know how.

Body:
Java allows for method overloading, unlike some other programming languages. This essentially means you can write this into your code:

public void remove(String name, int population,
            double area, String continent) {

    // your code goes here

}

// This will have a different method signature
// and will allow you to use remove("Canada")
// on its own.
public void remove(String name) {

    remove(name, 0, 0.0, "");

}

Note that for this to work properly, we would have to assume that .equals() ignores the population, area, and continent fields. If it does use these fields, you would need a way to determine the fields programmatically, perhaps by using a country dictionary.


问:
getting nested value by using node js / javascript

let data =
 [
    {
        "testingNewValue": {
            "en-US": "hello"
        }
    },
    {
        "testingNewValue": {
            "hi-IN": "hello "
        }
    },
    {
        "testingNewValue": {
            "us": "dummy"
        }
    },
    {
        "testingNewValue": {
            "xp-op-as": "value for testing"
        },
        "locationField": {
            "en-US": {
                "lat": 19.28563,
                "lon": 72.8691
            }
        }
    }
]

const value = Object.fromEntries(Object.entries(data).map(el=>(el[1]=Object.values(el[1])[0], el)))
    console.log(value);```
</div>
</div>
</p>
<p>I am trying to get value from the data json by using the object.fromEntries n object.entries but its not working as my expectation as I am expecting the value as</p>
<h2>Expectation</h2>
```{
  {
    testingNewValue:"hello"
  },
  {
    testingNewValue:"hello"
  },
  {
    testingNewValue:"dummy"
  },
  {
    testingNewValue:"value for testing",
    locationField:{
      lat: 19.28563,
      lon: 72.8691
    }
  }
}
```

but I am getting "0","1","2" as you can see in code snippet as I want to remove  all "en-US","hi-In" n all from data

How can I get my expectation

答:
Provided that you're actually after an array (as your current expected result isn't a valid structure), you should be taking the entires of each inner objects and then taking building your new object with fromEntries() after mapping each entry, rather then taking the entires of your entire data array which is causing the indexes to appear in your current result. The below code assumes you have one value within each inner object, and that each value is an object:

const data = [ { "testingNewValue": { "en-US": "hello" } }, { "testingNewValue": { "hi-IN": "hello " } }, { "testingNewValue": { "us": "dummy" } }, { "testingNewValue": { "xp-op-as": "value for testing" }, "locationField": { "en-US": { "lat": 19.28563, "lon": 72.8691 } } } ];

const value = data.map(el=>
  Object.fromEntries(Object.entries(el).map(([k, v]) => [k, Object.values(v)[0]]))
);
console.log(value);```

Body:
let data =
 [
    {
        "testingNewValue": {
            "en-US": "hello"
        }
    },
    {
        "testingNewValue": {
            "hi-IN": "hello "
        }
    },
    {
        "testingNewValue": {
            "us": "dummy"
        }
    },
    {
        "testingNewValue": {
            "xp-op-as": "value for testing"
        },
        "locationField": {
            "en-US": {
                "lat": 19.28563,
                "lon": 72.8691
            }
        }
    }
]

const value = Object.fromEntries(Object.entries(data).map(el=>(el[1]=Object.values(el[1])[0], el)))
    console.log(value);

I am trying to get value from the data json by using the object.fromEntries n object.entries but its not working as my expectation as I am expecting the value as

Expectation

{
  {
    testingNewValue:"hello"
  },
  {
    testingNewValue:"hello"
  },
  {
    testingNewValue:"dummy"
  },
  {
    testingNewValue:"value for testing",
    locationField:{
      lat: 19.28563,
      lon: 72.8691
    }
  }
}

but I am getting "0","1","2" as you can see in code snippet as I want to remove  all "en-US","hi-In" n all from data

How can I get my expectation


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

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

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

What I want to know is:

would there be any advantage to:

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

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

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

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

Could anyone enlightenment me? :)

答:
The key question is: does it make sense for more than one application to use the type? If so, it should be in a class library. If not, you may still want to put it in a class library just for the sake of separation (e.g. have one assembly per tier in an n-tier solution), but you could just put it in your application.

If your sanitization is general-purpose, then putting it in a class library would definitely be the right move.

I know of people who write almost no code in executable applications, and put almost everything in class libraries - so the application basically just wraps the class libraries. I don't tend to go quite that far myself...

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jon Skeet


问:
How can I use findViewById inside my Custom Non-Actitvity Class for android application?
Here, my activity class name is MapsActivity and my custom nonactivity class name is GeoFenceBroadCastReceiver. I have a SwitchCompact switch in the actitvity_maps.xml file and I can access it from MapsActivity.java by findViewById But when I want to access it from GeoFenceBroadCastReceiver I got an error on my application.
Now my questions are Can I use findViewById to access my SwitchCompact switch from GeoFenceBroadCastReceiver and how?

SwitchCompact switch code--

```<code><androidx.appcompat.widget.SwitchCompat
    android:id="@+id/vibrationSwitchId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_gravity="right"
    android:layout_marginRight="20dp"
    android:fontFamily="@font/lato_bold"
    android:scaleX="1.6"
    android:scaleY="1.6"
    android:textAllCaps="true"
    android:textOff="@string/text_off"
    android:textOn="@string/text_on"
    android:thumb="@drawable/thumb"
    app:showText="true"
    app:switchTextAppearance="@style/switch_style"
    app:thumbTint="#FFC107"
    app:track="@drawable/track"
    app:trackTint="#E6D7D7" />
</RelativeLayout>
</code>```

Switch Output

MapsActivity Code

```<code>package com.example.akash.mapsdemo;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import android.Manifest;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;

import android.location.Location;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingClient;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,  GoogleMap.OnMapLongClickListener{

private static final String TAG = "MapsActivity";

    private GeoFenceHelper geoFenceHelper;
    private GeofencingClient geofencingClient;

    private static final int BACKGROUND_LOCATION_ACCESS_REQUEST_CODE = 1002;

    private GoogleMap mMap;
    private GoogleApiClient client;
    private LocationRequest locationRequest;
    private Location lastLocation;
    private Marker currentLocationMarker;
    public static final int REQUEST_LOCATION_CODE = 99;
    int PROXIMITY_RADIUS = 10000;
    double latitude,longitude;

    private int FINE_LOCATION_ACCESS_REQUEST_CODE = 10001;

    private float GEOFENCE_RADIUS = 100;
    private String GEOFENCE_ID = "SOME_GEOFENCE_ID";

    void SwitchToast(SwitchCompat btnID, String textON, String textOFF, String modeName){
        btnID.setOnCheckedChangeListener((buttonView, isChecked) -> {
            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

            if (isChecked){
                if(modeName.equals("isVibration") ){
                    audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                    Toast.makeText(MapsActivity.this, textON, Toast.LENGTH_SHORT).show();
                }
                if (modeName.equals("isAlarm")){
                    audioManager.setRingerMode(AudioManager.STREAM_ALARM);
                    Toast.makeText(MapsActivity.this, textON, Toast.LENGTH_SHORT).show();
                }
            }
            else{
                if(modeName.equals("isVibration") ){
                    audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                    Toast.makeText(MapsActivity.this, textOFF, Toast.LENGTH_SHORT).show();
                }
                if (modeName.equals("isAlarm")){
                    audioManager.setRingerMode(AudioManager.STREAM_ALARM);
                    Toast.makeText(MapsActivity.this, textOFF, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        geofencingClient = LocationServices.getGeofencingClient(this);
        geoFenceHelper = new GeoFenceHelper(this);

        SwitchCompat vibrationSwitchID = findViewById(R.id.vibrationSwitchId);
        SwitchCompat alarmSwitchID = findViewById(R.id.alarmSwitchId);

        SwitchToast(vibrationSwitchID, "Vibration ON", "Vibration OFF", "isVibration");
        SwitchToast(alarmSwitchID, "Alarm ON", "Alarm OFF", "isAlarm");

        NotificationManager systemService = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) && !systemService.isNotificationPolicyAccessGranted()){
            startActivity(new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS));
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            checkLocationPermission();

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

        mapFragment.getMapAsync(this);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == FINE_LOCATION_ACCESS_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Now we have the permission
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                    return;
                }
                mMap.setMyLocationEnabled(true);
            } else {
                Toast.makeText(this, "We need location permission to run this app", Toast.LENGTH_LONG).show();
            }
        }
        if (requestCode == BACKGROUND_LOCATION_ACCESS_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Now we have the permission
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                    return;
                }
                Toast.makeText(this, "You can add geofences..", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Background location access is necessary for run this application", Toast.LENGTH_LONG).show();
            }
        }
    }

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

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }

        LatLng DIU = new LatLng(-34, 151);

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(DIU, 16));

        enableUserLocation();

        mMap.setOnMapLongClickListener(this);
    }

    public void enableUserLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {
            //ask for permission
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_LOCATION_ACCESS_REQUEST_CODE);
        }
    }

    @Override
    public void onMapLongClick(@NonNull LatLng latLng) {

        if (Build.VERSION.SDK_INT >= 29){
            //We need the background permission
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED){
                tryAddingGeofence(latLng);
            }else{
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, BACKGROUND_LOCATION_ACCESS_REQUEST_CODE);
            }
        }else{
            tryAddingGeofence(latLng);
        }
    }

    private void tryAddingGeofence(LatLng latLng){
        mMap.clear();
        addMarker(latLng);
        addCircle(latLng, GEOFENCE_RADIUS);
        addGeofence(latLng, GEOFENCE_RADIUS);
    }

    private void addGeofence(LatLng latLng, float radius) {
        Geofence geofence = geoFenceHelper.getGeoFence(GEOFENCE_ID, latLng, radius, Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_DWELL | Geofence.GEOFENCE_TRANSITION_EXIT);
        GeofencingRequest geofencingRequest = geoFenceHelper.getGeoFencingRequest(geofence);
        PendingIntent pendingIntent = geoFenceHelper.getPendingIntent();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        geofencingClient.addGeofences(geofencingRequest, pendingIntent)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void unused) {
                        Log.d(TAG, "onSuccess: GeoFence Added....");
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        String errorMessage = geoFenceHelper.getErrorString(e);
                        Log.d(TAG, "onFailure: "+ errorMessage);
                    }
                });
    }

    private void addMarker(LatLng latLng){
        MarkerOptions markerOptions = new MarkerOptions().position(latLng);
        mMap.addMarker(markerOptions);
    }

    private void addCircle(LatLng latLng, float radius){
        CircleOptions circleOptions = new CircleOptions();
        circleOptions.center(latLng);
        circleOptions.radius(radius);
        circleOptions.strokeColor(Color.argb(255, 255, 0, 0));
        circleOptions.fillColor(Color.argb(64, 255, 0, 0));
        circleOptions.strokeWidth(4);
        mMap.addCircle(circleOptions);
    }

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

    }

    @Override
    public void onLocationChanged(Location location) {

        latitude = location.getLatitude();
        longitude = location.getLongitude();
        lastLocation = location;

        if(currentLocationMarker != null)
        {
            currentLocationMarker.remove();

        }
        Log.d("lat = ",""+latitude);
        LatLng latLng = new LatLng(location.getLatitude() , location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);

        markerOptions.title("Current Location");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
        currentLocationMarker = mMap.addMarker(markerOptions);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomBy(10));

        if(client != null)
        {
            LocationServices.FusedLocationApi.removeLocationUpdates(client,this);
        }
    }

    public void onClick(View v)
    {
        Object dataTransfer[] = new Object[2];
        GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();

        LinearLayout settingViewId = findViewById(R.id.settingViewID);
        FrameLayout locationViewId = findViewById(R.id.locationViewID);
        FrameLayout mosqueViewId = findViewById(R.id.mosqueViewID);
        LinearLayout prayerTimeViewId = findViewById(R.id.prayerTimeViewID);

        switch(v.getId())
        {
            case R.id.settingsID:

                locationViewId.setVisibility(v.GONE);
                mosqueViewId.setVisibility(v.GONE);
                prayerTimeViewId.setVisibility(v.GONE);
                settingViewId.setVisibility(v.VISIBLE);

                Toast.makeText(MapsActivity.this, "Showing Nearby Hospitals", Toast.LENGTH_SHORT).show();
                break;

            case R.id.locationID:

                locationViewId.setVisibility(v.VISIBLE);
                mosqueViewId.setVisibility(v.GONE);
                prayerTimeViewId.setVisibility(v.GONE);
                settingViewId.setVisibility(v.GONE);

                Toast.makeText(MapsActivity.this, "Showing Nearby Schools", Toast.LENGTH_SHORT).show();
                break;
            case R.id.mosqueID:

                locationViewId.setVisibility(v.GONE);
                mosqueViewId.setVisibility(v.VISIBLE);
                prayerTimeViewId.setVisibility(v.GONE);
                settingViewId.setVisibility(v.GONE);

                mMap.clear();
                String mosque = "mosque";
                String url = getUrl(latitude, longitude, mosque);
                dataTransfer[0] = mMap;
                dataTransfer[1] = url;

                getNearbyPlacesData.execute(dataTransfer);

                Toast.makeText(MapsActivity.this, "Showing Nearby Mosque", Toast.LENGTH_SHORT).show();
                break;

            case R.id.prayerTimeID:

                locationViewId.setVisibility(v.GONE);
                mosqueViewId.setVisibility(v.GONE);
                prayerTimeViewId.setVisibility(v.VISIBLE);
                settingViewId.setVisibility(v.GONE);

                Toast.makeText(MapsActivity.this, "Showing Nearby Restaurants", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private String getUrl(double latitude , double longitude , String nearbyPlace)
    {

        StringBuilder googlePlaceUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        googlePlaceUrl.append("location="+latitude+","+longitude);
        googlePlaceUrl.append("&radius="+PROXIMITY_RADIUS);
        googlePlaceUrl.append("&type="+nearbyPlace);
        googlePlaceUrl.append("&sensor=true");
        googlePlaceUrl.append("&key="+getString(R.string.google_maps_key));

        Log.d("MapsActivity", "url = "+googlePlaceUrl.toString());

        return googlePlaceUrl.toString();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        locationRequest = new LocationRequest();
        locationRequest.setInterval(100);
        locationRequest.setFastestInterval(1000);
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED)
        {
            LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
        }
    }

    public boolean checkLocationPermission()
    {
        if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)  != PackageManager.PERMISSION_GRANTED )
        {

            ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION },REQUEST_LOCATION_CODE);
            return false;

        }
        else
            return true;
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }
}
</code>```

GeoFenceBroadCastReceiver code

```<code>package com.example.akash.mapsdemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.widget.SwitchCompat;

import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;

import java.util.List;

public class GeoFenceBroadCastReceiver extends BroadcastReceiver {

    private static final String TAG = "GeoFenceBroadCastReceiv";

//    public Activity mapsActivity;
//    public GeoFenceBroadCastReceiver(MapsActivity _mapsActivity) {
//        this.mapsActivity = _mapsActivity;
//        SwitchCompat btnID = this.mapsActivity.findViewById ( R.id.vibrationSwitchId );
//    }

    @Override
    public void onReceive(Context context, Intent intent) {
//        Toast.makeText(context, "Geofence Trigger", Toast.LENGTH_LONG).show();

        NotificationHelper notificationHelper = new NotificationHelper(context);

        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);

        if(geofencingEvent.hasError()){
            Log.d(TAG, "onReceiver: Error receiving geofence event");
            return;
        }

        List<Geofence> geofenceList = geofencingEvent.getTriggeringGeofences();
//
        for (Geofence geofence: geofenceList){
            Log.d(TAG, "onReceive: "+ geofence.getRequestId());
        }
//        Location location = geofencingEvent.getTriggeringLocation();

        int transitionType = geofencingEvent.getGeofenceTransition();

        switch (transitionType){
            case Geofence.GEOFENCE_TRANSITION_ENTER:
                Toast.makeText(context, "GEOFENCE_TRANSITION_ENTER", Toast.LENGTH_SHORT).show();
                notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_ENTER", "", MapsActivity.class);

                break;
            case Geofence.GEOFENCE_TRANSITION_DWELL:
                Toast.makeText(context, "GEOFENCE_TRANSITION_DWELL", Toast.LENGTH_SHORT).show();
                notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_DWELL", "", MapsActivity.class);
                break;
            case Geofence.GEOFENCE_TRANSITION_EXIT:
                Toast.makeText(context, "GEOFENCE_TRANSITION_EXIT", Toast.LENGTH_SHORT).show();
                notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_EXIT", "", MapsActivity.class);
                break;
        }

    }
}
</code>```

答: You don't want to do that.  A BroadcastReceiver is a separate context.  There's no promise that any activity exists when it goes off.  Instead, you should store the state of the switch in some place that the BroadcastReceiver can also see it.  A standard way of doing this would be in SharedPreferences.

Body:
Here, my activity class name is MapsActivity and my custom nonactivity class name is GeoFenceBroadCastReceiver. I have a SwitchCompact switch in the actitvity_maps.xml file and I can access it from MapsActivity.java by findViewById But when I want to access it from GeoFenceBroadCastReceiver I got an error on my application.
Now my questions are Can I use findViewById to access my SwitchCompact switch from GeoFenceBroadCastReceiver and how?

SwitchCompact switch code--

<androidx.appcompat.widget.SwitchCompat
    android:id="@+id/vibrationSwitchId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_gravity="right"
    android:layout_marginRight="20dp"
    android:fontFamily="@font/lato_bold"
    android:scaleX="1.6"
    android:scaleY="1.6"
    android:textAllCaps="true"
    android:textOff="@string/text_off"
    android:textOn="@string/text_on"
    android:thumb="@drawable/thumb"
    app:showText="true"
    app:switchTextAppearance="@style/switch_style"
    app:thumbTint="#FFC107"
    app:track="@drawable/track"
    app:trackTint="#E6D7D7" />
</RelativeLayout>

Switch Output

MapsActivity Code

package com.example.akash.mapsdemo;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import android.Manifest;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;

import android.location.Location;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingClient;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,  GoogleMap.OnMapLongClickListener{

private static final String TAG = "MapsActivity";

    private GeoFenceHelper geoFenceHelper;
    private GeofencingClient geofencingClient;

    private static final int BACKGROUND_LOCATION_ACCESS_REQUEST_CODE = 1002;

    private GoogleMap mMap;
    private GoogleApiClient client;
    private LocationRequest locationRequest;
    private Location lastLocation;
    private Marker currentLocationMarker;
    public static final int REQUEST_LOCATION_CODE = 99;
    int PROXIMITY_RADIUS = 10000;
    double latitude,longitude;

    private int FINE_LOCATION_ACCESS_REQUEST_CODE = 10001;

    private float GEOFENCE_RADIUS = 100;
    private String GEOFENCE_ID = "SOME_GEOFENCE_ID";

    void SwitchToast(SwitchCompat btnID, String textON, String textOFF, String modeName){
        btnID.setOnCheckedChangeListener((buttonView, isChecked) -> {
            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

            if (isChecked){
                if(modeName.equals("isVibration") ){
                    audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                    Toast.makeText(MapsActivity.this, textON, Toast.LENGTH_SHORT).show();
                }
                if (modeName.equals("isAlarm")){
                    audioManager.setRingerMode(AudioManager.STREAM_ALARM);
                    Toast.makeText(MapsActivity.this, textON, Toast.LENGTH_SHORT).show();
                }
            }
            else{
                if(modeName.equals("isVibration") ){
                    audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                    Toast.makeText(MapsActivity.this, textOFF, Toast.LENGTH_SHORT).show();
                }
                if (modeName.equals("isAlarm")){
                    audioManager.setRingerMode(AudioManager.STREAM_ALARM);
                    Toast.makeText(MapsActivity.this, textOFF, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        geofencingClient = LocationServices.getGeofencingClient(this);
        geoFenceHelper = new GeoFenceHelper(this);

        SwitchCompat vibrationSwitchID = findViewById(R.id.vibrationSwitchId);
        SwitchCompat alarmSwitchID = findViewById(R.id.alarmSwitchId);

        SwitchToast(vibrationSwitchID, "Vibration ON", "Vibration OFF", "isVibration");
        SwitchToast(alarmSwitchID, "Alarm ON", "Alarm OFF", "isAlarm");

        NotificationManager systemService = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) && !systemService.isNotificationPolicyAccessGranted()){
            startActivity(new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS));
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            checkLocationPermission();

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

        mapFragment.getMapAsync(this);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == FINE_LOCATION_ACCESS_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Now we have the permission
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                    return;
                }
                mMap.setMyLocationEnabled(true);
            } else {
                Toast.makeText(this, "We need location permission to run this app", Toast.LENGTH_LONG).show();
            }
        }
        if (requestCode == BACKGROUND_LOCATION_ACCESS_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Now we have the permission
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                    return;
                }
                Toast.makeText(this, "You can add geofences..", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Background location access is necessary for run this application", Toast.LENGTH_LONG).show();
            }
        }
    }

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

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }

        LatLng DIU = new LatLng(-34, 151);

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(DIU, 16));

        enableUserLocation();

        mMap.setOnMapLongClickListener(this);
    }

    public void enableUserLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {
            //ask for permission
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_LOCATION_ACCESS_REQUEST_CODE);
        }
    }

    @Override
    public void onMapLongClick(@NonNull LatLng latLng) {

        if (Build.VERSION.SDK_INT >= 29){
            //We need the background permission
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED){
                tryAddingGeofence(latLng);
            }else{
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, BACKGROUND_LOCATION_ACCESS_REQUEST_CODE);
            }
        }else{
            tryAddingGeofence(latLng);
        }
    }

    private void tryAddingGeofence(LatLng latLng){
        mMap.clear();
        addMarker(latLng);
        addCircle(latLng, GEOFENCE_RADIUS);
        addGeofence(latLng, GEOFENCE_RADIUS);
    }

    private void addGeofence(LatLng latLng, float radius) {
        Geofence geofence = geoFenceHelper.getGeoFence(GEOFENCE_ID, latLng, radius, Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_DWELL | Geofence.GEOFENCE_TRANSITION_EXIT);
        GeofencingRequest geofencingRequest = geoFenceHelper.getGeoFencingRequest(geofence);
        PendingIntent pendingIntent = geoFenceHelper.getPendingIntent();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        geofencingClient.addGeofences(geofencingRequest, pendingIntent)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void unused) {
                        Log.d(TAG, "onSuccess: GeoFence Added....");
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        String errorMessage = geoFenceHelper.getErrorString(e);
                        Log.d(TAG, "onFailure: "+ errorMessage);
                    }
                });
    }

    private void addMarker(LatLng latLng){
        MarkerOptions markerOptions = new MarkerOptions().position(latLng);
        mMap.addMarker(markerOptions);
    }

    private void addCircle(LatLng latLng, float radius){
        CircleOptions circleOptions = new CircleOptions();
        circleOptions.center(latLng);
        circleOptions.radius(radius);
        circleOptions.strokeColor(Color.argb(255, 255, 0, 0));
        circleOptions.fillColor(Color.argb(64, 255, 0, 0));
        circleOptions.strokeWidth(4);
        mMap.addCircle(circleOptions);
    }

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

    }

    @Override
    public void onLocationChanged(Location location) {

        latitude = location.getLatitude();
        longitude = location.getLongitude();
        lastLocation = location;

        if(currentLocationMarker != null)
        {
            currentLocationMarker.remove();

        }
        Log.d("lat = ",""+latitude);
        LatLng latLng = new LatLng(location.getLatitude() , location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);

        markerOptions.title("Current Location");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
        currentLocationMarker = mMap.addMarker(markerOptions);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomBy(10));

        if(client != null)
        {
            LocationServices.FusedLocationApi.removeLocationUpdates(client,this);
        }
    }

    public void onClick(View v)
    {
        Object dataTransfer[] = new Object[2];
        GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();

        LinearLayout settingViewId = findViewById(R.id.settingViewID);
        FrameLayout locationViewId = findViewById(R.id.locationViewID);
        FrameLayout mosqueViewId = findViewById(R.id.mosqueViewID);
        LinearLayout prayerTimeViewId = findViewById(R.id.prayerTimeViewID);

        switch(v.getId())
        {
            case R.id.settingsID:

                locationViewId.setVisibility(v.GONE);
                mosqueViewId.setVisibility(v.GONE);
                prayerTimeViewId.setVisibility(v.GONE);
                settingViewId.setVisibility(v.VISIBLE);

                Toast.makeText(MapsActivity.this, "Showing Nearby Hospitals", Toast.LENGTH_SHORT).show();
                break;

            case R.id.locationID:

                locationViewId.setVisibility(v.VISIBLE);
                mosqueViewId.setVisibility(v.GONE);
                prayerTimeViewId.setVisibility(v.GONE);
                settingViewId.setVisibility(v.GONE);

                Toast.makeText(MapsActivity.this, "Showing Nearby Schools", Toast.LENGTH_SHORT).show();
                break;
            case R.id.mosqueID:

                locationViewId.setVisibility(v.GONE);
                mosqueViewId.setVisibility(v.VISIBLE);
                prayerTimeViewId.setVisibility(v.GONE);
                settingViewId.setVisibility(v.GONE);

                mMap.clear();
                String mosque = "mosque";
                String url = getUrl(latitude, longitude, mosque);
                dataTransfer[0] = mMap;
                dataTransfer[1] = url;

                getNearbyPlacesData.execute(dataTransfer);

                Toast.makeText(MapsActivity.this, "Showing Nearby Mosque", Toast.LENGTH_SHORT).show();
                break;

            case R.id.prayerTimeID:

                locationViewId.setVisibility(v.GONE);
                mosqueViewId.setVisibility(v.GONE);
                prayerTimeViewId.setVisibility(v.VISIBLE);
                settingViewId.setVisibility(v.GONE);

                Toast.makeText(MapsActivity.this, "Showing Nearby Restaurants", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private String getUrl(double latitude , double longitude , String nearbyPlace)
    {

        StringBuilder googlePlaceUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        googlePlaceUrl.append("location="+latitude+","+longitude);
        googlePlaceUrl.append("&radius="+PROXIMITY_RADIUS);
        googlePlaceUrl.append("&type="+nearbyPlace);
        googlePlaceUrl.append("&sensor=true");
        googlePlaceUrl.append("&key="+getString(R.string.google_maps_key));

        Log.d("MapsActivity", "url = "+googlePlaceUrl.toString());

        return googlePlaceUrl.toString();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        locationRequest = new LocationRequest();
        locationRequest.setInterval(100);
        locationRequest.setFastestInterval(1000);
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED)
        {
            LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
        }
    }

    public boolean checkLocationPermission()
    {
        if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)  != PackageManager.PERMISSION_GRANTED )
        {

            ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION },REQUEST_LOCATION_CODE);
            return false;

        }
        else
            return true;
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }
}

GeoFenceBroadCastReceiver code

package com.example.akash.mapsdemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.widget.SwitchCompat;

import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;

import java.util.List;

public class GeoFenceBroadCastReceiver extends BroadcastReceiver {

    private static final String TAG = "GeoFenceBroadCastReceiv";

//    public Activity mapsActivity;
//    public GeoFenceBroadCastReceiver(MapsActivity _mapsActivity) {
//        this.mapsActivity = _mapsActivity;
//        SwitchCompat btnID = this.mapsActivity.findViewById ( R.id.vibrationSwitchId );
//    }

    @Override
    public void onReceive(Context context, Intent intent) {
//        Toast.makeText(context, "Geofence Trigger", Toast.LENGTH_LONG).show();

        NotificationHelper notificationHelper = new NotificationHelper(context);

        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);

        if(geofencingEvent.hasError()){
            Log.d(TAG, "onReceiver: Error receiving geofence event");
            return;
        }

        List<Geofence> geofenceList = geofencingEvent.getTriggeringGeofences();
//
        for (Geofence geofence: geofenceList){
            Log.d(TAG, "onReceive: "+ geofence.getRequestId());
        }
//        Location location = geofencingEvent.getTriggeringLocation();

        int transitionType = geofencingEvent.getGeofenceTransition();

        switch (transitionType){
            case Geofence.GEOFENCE_TRANSITION_ENTER:
                Toast.makeText(context, "GEOFENCE_TRANSITION_ENTER", Toast.LENGTH_SHORT).show();
                notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_ENTER", "", MapsActivity.class);

                break;
            case Geofence.GEOFENCE_TRANSITION_DWELL:
                Toast.makeText(context, "GEOFENCE_TRANSITION_DWELL", Toast.LENGTH_SHORT).show();
                notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_DWELL", "", MapsActivity.class);
                break;
            case Geofence.GEOFENCE_TRANSITION_EXIT:
                Toast.makeText(context, "GEOFENCE_TRANSITION_EXIT", Toast.LENGTH_SHORT).show();
                notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_EXIT", "", MapsActivity.class);
                break;
        }

    }
}


问:
How can I restrict whole page to re-render in React?
I have js file which contains data that I am rendering on the page using useState. I have a button Display which uses fetch API to get more data and display below the existing data.

I would like to display Loading when Display button is clicked till data arrives.

Problem is whole page is re rendered with Loading. I would like to display data that I am getting from js file as it is and just display Loading below Display button till I get more data from API

```<code> const [isLoading, setIsLoading] = useState(false);

  if (isLoading) {
    return <h2>Loading..</h2>;
  }
</code>```
```<code>const fetchData = async () => {
    setIsLoading(true);
    const response = await fetch(fetchDataUrl);
    const data = await response.json();
    setIsLoading(false);
    setMoreData(data.datas);
  };
</code>```

答:
const Component = () => {
    const [isLoading, setIsLoading] = useState(false);
    const fetchData = () => {
         setIsLoading(true)
         fetch(someUrl)
            .then(data => {
                setData(data)
                setIsLoading(false)
         });
    }
    return (
    <>
        {yourData.map((data) => <IdkMaybeItsSomeComponent data={data}>}

        { isLoading
          ?
Loading...

          : <button onClick={fetchData}>Get More Data</button> }
    </>
    )
}
```

How about something like that? Only showing the loading at the bottom when you are currently loading data.

Body:
I have js file which contains data that I am rendering on the page using useState. I have a button Display which uses fetch API to get more data and display below the existing data.

I would like to display Loading when Display button is clicked till data arrives.

Problem is whole page is re rendered with Loading. I would like to display data that I am getting from js file as it is and just display Loading below Display button till I get more data from API

 const [isLoading, setIsLoading] = useState(false);

  if (isLoading) {
    return
Loading..
;
  }

const fetchData = async () => {
    setIsLoading(true);
    const response = await fetch(fetchDataUrl);
    const data = await response.json();
    setIsLoading(false);
    setMoreData(data.datas);
  };

Body:
const Component = () => {
    const [isLoading, setIsLoading] = useState(false);
    const fetchData = () => {
         setIsLoading(true)
         fetch(someUrl)
            .then(data => {
                setData(data)
                setIsLoading(false)
         });
    }
    return (
    <>
        {yourData.map((data) => <IdkMaybeItsSomeComponent data={data}>}

        { isLoading
          ? <h2>Loading...</h2>
          : <button onClick={fetchData}>Get More Data</button> }
    </>
    )
}

How about something like that? Only showing the loading at the bottom when you are currently loading data.


问:
Create a new df in pandas from existing one?
I am doing a project on movies data.

The sample dataset looks like :

The column genres have 21 unique values.

I want to create a new table/dataframe so that the table will contains the average ratings for the each genres for every user, like

I got the list of genres using the code below:

```<code>def split(sent):
    return (sent.split())

new_genres=set()

for i in range(len(genres)):
    a=split(genres[i])
    for g in a:
        new_genres.add(g)

new_genres
</code>```

答:
Setup:

```<code>In [905]: df = pd.DataFrame({'userID':[1,2,3,3,2], 'id':[110, 147, 858, 1246, 1968], 'rating':[1.0, 4.5, 5.0, 5.0, 4.0], 'genres':['Drama Mystery Romance', 'Drama', 'Comedy Drama Romance', 'Drama', 'Drama Comedy Romance']}
     ...: )

In [906]: df
Out[906]:
   userID    id  rating                 genres
0       1   110     1.0  Drama Mystery Romance
1       2   147     4.5                  Drama
2       3   858     5.0   Comedy Drama Romance
3       3  1246     5.0                  Drama
4       2  1968     4.0   Drama Comedy Romance
</code>```

Use Series.str.split, df.explode with df.pivot_table:

```<code>In [907]: df['genres'] = df['genres'].str.split()
In [910]: res = df.explode('genres').pivot_table(index='userID', columns='genres', values='rating', aggfunc='mean').fillna(0, downcast='infer')

In [911]: res
Out[911]:
genres  Comedy  Drama  Mystery  Romance
userID
1            0   1.00        1        1
2            4   4.25        0        4
3            5   5.00        0        5
</code>```

Body:
I am doing a project on movies data.

The sample dataset looks like :

The column genres have 21 unique values.

I want to create a new table/dataframe so that the table will contains the average ratings for the each genres for every user, like

I got the list of genres using the code below:

def split(sent):
    return (sent.split())

new_genres=set()

for i in range(len(genres)):
    a=split(genres[i])
    for g in a:
        new_genres.add(g)

new_genres

Body:
Setup:

In [905]: df = pd.DataFrame({'userID':[1,2,3,3,2], 'id':[110, 147, 858, 1246, 1968], 'rating':[1.0, 4.5, 5.0, 5.0, 4.0], 'genres':['Drama Mystery Romance', 'Drama', 'Comedy Drama Romance', 'Drama', 'Drama Comedy Romance']}
     ...: )

In [906]: df
Out[906]:
   userID    id  rating                 genres
0       1   110     1.0  Drama Mystery Romance
1       2   147     4.5                  Drama
2       3   858     5.0   Comedy Drama Romance
3       3  1246     5.0                  Drama
4       2  1968     4.0   Drama Comedy Romance

Use Series.str.split, df.explode with df.pivot_table:

In [907]: df['genres'] = df['genres'].str.split()
In [910]: res = df.explode('genres').pivot_table(index='userID', columns='genres', values='rating', aggfunc='mean').fillna(0, downcast='infer')

In [911]: res
Out[911]:
genres  Comedy  Drama  Mystery  Romance
userID
1            0   1.00        1        1
2            4   4.25        0        4
3            5   5.00        0        5


问:
use of google sign in as both sign up and sign in both
i have a doubt is that how can i use google sign in method through firebase as both sign up and login .
i want to make app in which you have to first sign up through only google account to prove that given mail is true and not made up .and after signing up through google account it redirect us to next activity which contains name , adress , like  stuff.

But i want to show this second activity only once at the time of google sign up ; otherwise for login time it automatically fetch this details .

So i have a doubt that how can use this authentication service as both sign up and login.

thank you

答: Empower Google Sign-In within the Firebase console: In the Firebase support, open the Auth section. On the Sign in strategy tab, empower the Google sign-in strategy and press Spare.</p>


问:
Vue js 3 Passing dynamic model value inside a v-for
I'm working on a product page which has a gallery and this gallery needs to change when different options is selected.

to simplify, imagine this is the gallery:

<swiper-slide v-for="image in product.option" :key="image.id">
```
<p>and I've radio buttons like this:</p>
<pre class="lang-html prettyprint-override"><code><RadioGroup v-model="optionChoice">
</code>```

I need to somehow pass optionChoice to v-for so it dynamically change when user selects an option. something like this:

<swiper-slide v-for="image in product.{{optionChoice}}" :key="image.id">
```

Can someone guide me?

答:
In JavaScript, bracket notation is used to reference an object property by a dynamic key:

const product = { name: 'john', age: 100 }

let optionChoice = 'name'
console.log(product[optionChoice]) // => 'john'

optionChoice = 'age'
console.log(product[optionChoice]) // => 100```
</div>
</div>
</p>
<p>The <code>v-for</code> value is a JavaScript expression, so the same solution applies:</p>
<pre class="lang-html prettyprint-override"><code><swiper-slide v-for="image in product[optionChoice]" :key="image.id">

</code>```

demo

Body:
I'm working on a product page which has a gallery and this gallery needs to change when different options is selected.

to simplify, imagine this is the gallery:

<swiper-slide v-for="image in product.option" :key="image.id">

and I've radio buttons like this:

<RadioGroup v-model="optionChoice">

I need to somehow pass optionChoice to v-for so it dynamically change when user selects an option. something like this:

<swiper-slide v-for="image in product.{{optionChoice}}" :key="image.id">

Can someone guide me?

Body:
In JavaScript, bracket notation is used to reference an object property by a dynamic key:

const product = { name: 'john', age: 100 }

let optionChoice = 'name'
console.log(product[optionChoice]) // => 'john'

optionChoice = 'age'
console.log(product[optionChoice]) // => 100

The v-for value is a JavaScript expression, so the same solution applies:

<swiper-slide v-for="image in product[optionChoice]" :key="image.id">

demo


问:
numpy.dot for dimensions > 2
I am trying to understand how dot product works for dimensions more than 2.

The documentation says:

If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last # axis of a and the second-to-last axis of b:

```<code>dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
</code>```

I don't understand this rule -- where does it come from? Why is it the last axis of a and the second-to-last axis of b?

答:
Here's my best attempt at making sense of the rule.

Suppose that a is a p1 x ... x pm-1 x pm array and that b is a q1 x ... x qn-1 x qn array. The dot function seems to be interpreting a as an p1 x ... x pm-2 array of pm-1 x pm matrices, and b as a q1 x ... x qn-2 array of qn-1 x qn matrices.

With that established, the entry dot(a,b)[i_1,...,i_(n-2),k_1,j_1,...,j_(m-2),k_2] is the k_1,k_2 entry of the matrix product
dot(a[i_1,...,i_(n-2),:,:],b[j_1,...,j_(m-2),:,:]) of a pm-1 x pm with a qn-1 x qn. Notably, this product is only defined if pm=qn-1.

Title: numpy.dot for dimensions > 2

Body:
I am trying to understand how dot product works for dimensions more than 2.

The documentation says:

If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last # axis of a and the second-to-last axis of b:

dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

I don't understand this rule -- where does it come from? Why is it the last axis of a and the second-to-last axis of b?


问:
Swing : detecting onKeyPressed
I'm trying to do a very simple thing : trigger an action when the user presses on a key of the keyboard

the keys I would like to map are :

key +

key -

key delete

ctrl+c

ctrl+v

public class keytestmain extends Applet{

```<code>//Called when this applet is loaded into the browser.
public void init() {
    //Execute a job on the event-dispatching thread; creating this applet's GUI.
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                JLabel lbl = new JLabel("Hello World");
                add(lbl);
                JPanel p = new JPanel();
                p.setBackground(Color.green);
                p.setMinimumSize(new Dimension(100,100));
                p.setPreferredSize(new Dimension(100,100));
                p.setMaximumSize(new Dimension(100,100));
                InputMap inputMap = new InputMap();

                // Add a KeyStroke
                inputMap.put(KeyStroke.getKeyStroke("SPACE"), "actionName");

                inputMap.setParent(p.getInputMap(JComponent.WHEN_FOCUSED));
                p.setInputMap(JComponent.WHEN_FOCUSED, inputMap);
                add(p);
            }
        });
    } catch (Exception e) {
        System.err.println("createGUI didn't complete successfully");
    }

}
</code>```

}

but nothing works

Any ideas?

答: I would use Key Bindings, instead of KeyListeners. This is more reliable as it doesn't have many focus issues. Also KeyListeners is a relatively old AWT solution, so depending on your JDE, the command may have been depracated.</p>

Title: Swing : detecting onKeyPressed

Body:
I'm trying to do a very simple thing : trigger an action when the user presses on a key of the keyboard

the keys I would like to map are :

key +

key -

key delete

ctrl+c

ctrl+v

public class keytestmain extends Applet{

//Called when this applet is loaded into the browser.
public void init() {
    //Execute a job on the event-dispatching thread; creating this applet's GUI.
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                JLabel lbl = new JLabel("Hello World");
                add(lbl);
                JPanel p = new JPanel();
                p.setBackground(Color.green);
                p.setMinimumSize(new Dimension(100,100));
                p.setPreferredSize(new Dimension(100,100));
                p.setMaximumSize(new Dimension(100,100));
                InputMap inputMap = new InputMap();

                // Add a KeyStroke
                inputMap.put(KeyStroke.getKeyStroke("SPACE"), "actionName");

                inputMap.setParent(p.getInputMap(JComponent.WHEN_FOCUSED));
                p.setInputMap(JComponent.WHEN_FOCUSED, inputMap);
                add(p);
            }
        });
    } catch (Exception e) {
        System.err.println("createGUI didn't complete successfully");
    }

}

}

but nothing works

Any ideas?


问:
How to append np.array?
I have an np.array d1 of (3,6), and an np.array a4 of (6,).

How can I combine the two np.arrays to form an np.array d2 of (4,6)?

My code is as follows:

```<code>import numpy as np
a1=np.array(range(6))
a2=a1+2
a3=a2+3
a4=a3+4
d1=np.array([a1,a2,a3])
d1.shape
</code>```
```<code>Out[44]: (3, 6)
</code>```
```<code>d2=np.array([a1,a2,a3,a4])
d2.shape
d2
</code>```
```<code>Out[45]: (4, 6)
Out[46]:
array([[ 0,  1,  2,  3,  4,  5],
       [ 2,  3,  4,  5,  6,  7],
       [ 5,  6,  7,  8,  9, 10],
       [ 9, 10, 11, 12, 13, 14]])
</code>```

How to get d2 from d1 and a4?

I tried np.insert and np.append, but maybe my usage is wrong and I didn't get the correct result.

Title: How to append np.array?

Body:
I have an np.array d1 of (3,6), and an np.array a4 of (6,).

How can I combine the two np.arrays to form an np.array d2 of (4,6)?

My code is as follows:

import numpy as np
a1=np.array(range(6))
a2=a1+2
a3=a2+3
a4=a3+4
d1=np.array([a1,a2,a3])
d1.shape

Out[44]: (3, 6)

d2=np.array([a1,a2,a3,a4])
d2.shape
d2

Out[45]: (4, 6)
Out[46]:
array([[ 0,  1,  2,  3,  4,  5],
       [ 2,  3,  4,  5,  6,  7],
       [ 5,  6,  7,  8,  9, 10],
       [ 9, 10, 11, 12, 13, 14]])

How to get d2 from d1 and a4?

I tried np.insert and np.append, but maybe my usage is wrong and I didn't get the correct result.

Body:
Firstly you need to reshape a4 which has currently the shape of (6,)

a4 = a4.reshape(1,-1)  # shape=(1,6)

then use np.concatenate

d2 = np.concatenate((d1, a4), axis=0)

output:

array([[ 0,  1,  2,  3,  4,  5],
       [ 2,  3,  4,  5,  6,  7],
       [ 5,  6,  7,  8,  9, 10],
       [ 9, 10, 11, 12, 13, 14]])


问:
How to set the default mimetype to render in VSCode Jupyter Notebook
How can i change the default mimetype to render in a Jupyter Notebook inside VSCode?

答:
Suppose you want to make Jupyter use "text/plain" as renderer default.

Step 1: in the output cell, choose text/plain

Step 2: Open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P on Mac), search for "mime" and click: "Notebook: Save Mimetype Display Order"

Step 3: You will be prompted to choose either to enable that default setting globally (choose "User Settings") or locally for that specific workspace (choose "Workspace Settings")

Notebook: Save Mimetype Display Order


问:
How do I request search results from google without trigerring a 429 error( too many requests for url)?
My script makes only one request from 'www.google.com/search?q=' despite this it always triggers a 429 error( too many requests for url). The script simply attempts to use python's 3rd party requests library to retrieve the search page for a word entered as a command line variable. Solutions I have tried include adding a header specifying my user agent.This is all of the code it is quite small.

```<code>import requests, sys, webbrowser, bs4

headers = {'User-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0' }
print('Googling...') # display text while downloading the Google page
res = requests.get('http://www.google.com/search?q=' + ' '.join(sys.argv[1:]), headers=headers)
res.raise_for_status()
</code>```

The error reads as follows

```<code>  File "lucky.py", line 11, in <module>
    res.raise_for_status()
  File "C:\ProgramData\Anaconda3\lib\site-packages\requests\models.py", line 941, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 429 Client Error: Too Many Requests for url: https://www.google.com/sorry/index?continue=https://www.google.com/search%3Fq%3Dred&q=EgRmsF6JGJ_0-48GIhDND5xins41tXhPPRNDx_-jMgFy
</code>```

Thanks

Edited***

So the code runs when I use an online compiler but not on my PC...

答:
The code works for me Here .

HTTPError: 429 Client Error: Too Many Requests * this occurs because server blocks the ip temporary as it thinks you are trying to spam something by sending to many requests in a short amount of time. It's  a security measurement by the server

Body:
My script makes only one request from 'www.google.com/search?q=' despite this it always triggers a 429 error( too many requests for url). The script simply attempts to use python's 3rd party requests library to retrieve the search page for a word entered as a command line variable. Solutions I have tried include adding a header specifying my user agent.This is all of the code it is quite small.

import requests, sys, webbrowser, bs4

headers = {'User-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0' }
print('Googling...') # display text while downloading the Google page
res = requests.get('http://www.google.com/search?q=' + ' '.join(sys.argv[1:]), headers=headers)
res.raise_for_status()

The error reads as follows

  File "lucky.py", line 11, in <module>
    res.raise_for_status()
  File "C:\ProgramData\Anaconda3\lib\site-packages\requests\models.py", line 941, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 429 Client Error: Too Many Requests for url: https://www.google.com/sorry/index?continue=https://www.google.com/search%3Fq%3Dred&q=EgRmsF6JGJ_0-48GIhDND5xins41tXhPPRNDx_-jMgFy

Thanks

Edited***

So the code runs when I use an online compiler but not on my PC...


问:
Text column in R - Trying to count the keywords sequentially
I am working on a dataset that has a text column. The text has many sentences separated by a semi-colon ';'. I am trying to get a word count in a new column in dataframe for words that match my keyword. However, in one sentence, if there are repeated keywords, they should be considered only once.

For instance -

The section 201 solar trade case on cells and modules; Issues relating to section 201 tariffs on imported goods

Solar panels, Tawian tariffs, trade

Trade issues impacting the solar industry

are the text in one column of the dataframe.
My keywords include solar, solar panels, section 201

I want to count the words in each sentence that match my keywords but if both or all words are there in the sentence, then it is counted only once. Word counts should only consider keywords in different sentences. If one sentence doesn't have a specific keyword, then move towards finding the second keyword.

My output should be -
word_count
2 (as section 201 is mentioned in both sentences, we do not search for solar because the first word in the keyword list matched)
1 (as only solar word is there)
1 (as only solar word is there)

Please suggest a way to resolve this issue. It is a crucial part of my research work. Thanks.

Kind Regards,
Preety

答:
I would first split your text column into multiple columns using tidyr::separate(); then search for your key phrases within each of these, using stringr::str_detect() or base regex functions; then sum across columns using rowSums(dplyr::across()). Like so:

```<code>library(tidyverse)
keywords <- paste("solar", "section 201", sep = "|")
df <- tibble(
  text = c(
    "The section 201 solar trade case on cells and modules; Issues relating to section 201 tariffs on imported goods",
"Solar panels; Tawian tariffs; trade",
"Trade issues impacting the solar industry"
  )
)

df <- df %>%
  separate(text, into = c("text1", "text2", "text3"), sep = ";", fill = "right") %>%
  mutate(
    count = rowSums(
      across(text1:text3, ~ str_detect(str_to_lower(.x), keywords)),
      na.rm = TRUE
    )
  )
</code>```

The count column then contains the results you predicted:

```<code>df %>%
  select(count)

# A tibble: 3 x 1
#   count
#   <dbl>
# 1     2
# 2     1
# 3     1
</code>```

Body:
I would first split your text column into multiple columns using tidyr::separate(); then search for your key phrases within each of these, using stringr::str_detect() or base regex functions; then sum across columns using rowSums(dplyr::across()). Like so:

library(tidyverse)
keywords <- paste("solar", "section 201", sep = "|")
df <- tibble(
  text = c(
    "The section 201 solar trade case on cells and modules; Issues relating to section 201 tariffs on imported goods",
"Solar panels; Tawian tariffs; trade",
"Trade issues impacting the solar industry"
  )
)

df <- df %>%
  separate(text, into = c("text1", "text2", "text3"), sep = ";", fill = "right") %>%
  mutate(
    count = rowSums(
      across(text1:text3, ~ str_detect(str_to_lower(.x), keywords)),
      na.rm = TRUE
    )
  )

The count column then contains the results you predicted:

df %>%
  select(count)

# A tibble: 3 x 1
#   count
#   <dbl>
# 1     2
# 2     1
# 3     1


问:
how to set particular field in array of object in mongodb aggregation or pipeline query along with conditional update of the other field in document?
```<code>{
id:1,
projectName:'Project1'
start:"17-04-2022",
end:"12-05-2020",
tasks:[
{
taskId:1,
taskName:'first task',
taskStart:'20-04-2022',
taskEnd:'25-04-2022'
},

{
taskid:2,
taskName:'second task',
taskStart:'25-04-2022',
taskEnd:'30-04-2022'
},

]
},
{
id:2,
projectName:'Project2'
start:"27-04-2022",
end:"22-05-2020",
tasks:[
{
taskId:1,
taskName:'first task',
taskStart:'30-04-2022',
taskEnd:'12-05-2022'
},

{
taskid:2,
taskName:'second task',
taskStart:'28-04-2022',
taskEnd:'15-05-2022'
},

]
}
</code>```

how to update field "taskEnd" of tasks array with document id=1 and taskID=1 AND while updating if data from the frontend which is used to update the "taskEnd" exceeds "end" field, update the "end" field also with same value.

Thanks in Advance,

I know how to update specific field for the array of objects and conditional update of field with two separate queries.

can it be done with single query?

答:
You can do this with a pipeline update instead of using an update document.
I'm assuming you are getting the input date in the same format as the other dates.

var input_date = "11-05-2020";
db.collection.update({
  id: 1
},
[
  {
    $addFields: {
      end: {
        $cond: [
          {
            $gt: [
              {
                $dateFromString: {
                  dateString: "$end"
                }
              },
              {
                $dateFromString: {
                  dateString: input_date
                }
              }
            ]
          },
          "$end",
          input_date
        ]
      },
      tasks: {
        $map: {
          input: "$tasks",
          as: "elem",
          in: {
            $cond: [
              {
                $eq: [
                  "$$elem.taskId",
                  1
                ]
              },
              {
                $setField: {
                  field: "taskEnd",
                  input: "$$elem",
                  value: input_date
                }
              },
              "$$elem"
            ]
          }
        }
      }
    }
  }
])
```

Body:
{
id:1,
projectName:'Project1'
start:"17-04-2022",
end:"12-05-2020",
tasks:[
{
taskId:1,
taskName:'first task',
taskStart:'20-04-2022',
taskEnd:'25-04-2022'
},

{
taskid:2,
taskName:'second task',
taskStart:'25-04-2022',
taskEnd:'30-04-2022'
},

]
},
{
id:2,
projectName:'Project2'
start:"27-04-2022",
end:"22-05-2020",
tasks:[
{
taskId:1,
taskName:'first task',
taskStart:'30-04-2022',
taskEnd:'12-05-2022'
},

{
taskid:2,
taskName:'second task',
taskStart:'28-04-2022',
taskEnd:'15-05-2022'
},

]
}

how to update field "taskEnd" of tasks array with document id=1 and taskID=1 AND while updating if data from the frontend which is used to update the "taskEnd" exceeds "end" field, update the "end" field also with same value.

Thanks in Advance,

I know how to update specific field for the array of objects and conditional update of field with two separate queries.

can it be done with single query?


问:
Setting SQL Linked Server using DSN Connection
We have Ctree Database ODBC Drivers which is installed and configured on our local system. We have DSN Connection which is ready to use.

Using DSN Connection, i need to establish SQL Linked Server Connection. I am very new to SQL Linked Server Connection settings. I am looking for more articles and help which could help me to establish SQL Linked Server Connection settings with DSN Connection.

答:
Use something like this (the name of the linked server will be CTREESRV):</p>

```<code>USE [master]
GO
EXEC master.dbo.sp_addlinkedserver @server = N'CTREESRV', @srvproduct=N'Ctree', @provider=N'MSDASQL', @datasrc=N'DSN_NAME_HERE', @location=N'SOMETHING', @provstr=N'DNS=DSN_NAME_HERE;UID=DSN_USRNAME_HERE;PWD=DSN_PASSWD_HERE', @catalog=N'DATABASENAME_HERE'

GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'collation compatible', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'data access', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'dist', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'pub', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'rpc', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'rpc out', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'sub', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'connect timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'collation name', @optvalue=null
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'lazy schema validation', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'query timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'use remote collation', @optvalue=N'true'
GO
USE [master]
GO
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname = N'CTREESRV', @locallogin = NULL , @useself = N'False'
GO
</code>```

Body:
Use something like this (the name of the linked server will be CTREESRV):

USE [master]
GO
EXEC master.dbo.sp_addlinkedserver @server = N'CTREESRV', @srvproduct=N'Ctree', @provider=N'MSDASQL', @datasrc=N'DSN_NAME_HERE', @location=N'SOMETHING', @provstr=N'DNS=DSN_NAME_HERE;UID=DSN_USRNAME_HERE;PWD=DSN_PASSWD_HERE', @catalog=N'DATABASENAME_HERE'

GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'collation compatible', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'data access', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'dist', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'pub', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'rpc', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'rpc out', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'sub', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'connect timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'collation name', @optvalue=null
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'lazy schema validation', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'query timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'CTREESRV', @optname=N'use remote collation', @optvalue=N'true'
GO
USE [master]
GO
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname = N'CTREESRV', @locallogin = NULL , @useself = N'False'
GO


问:
Replace BB code with hyperlinks for ALL occurrences
I have this replace code to parse BB code and convert links to clickable hyperlinks. This works for one link, however if there is more than one link in the string, it merges them together in one long link, hyperlinking all text in between. I thought the [g] flag accounted for this, but doesn't appear to work.

```<code>about = about.replace(/\[url=([^\s\]]+)\s*\](.*(?=\[\/url\]))\[\/url\]/g, '<a href="$1" target="_blank">$2</a>')
</code>```

答:
I worked it out with the following:

about = about.replace(/\[url=([^\]]+)\](.*?)\[\/url\]/gi, "$2")

Body:
I have this replace code to parse BB code and convert links to clickable hyperlinks. This works for one link, however if there is more than one link in the string, it merges them together in one long link, hyperlinking all text in between. I thought the [g] flag accounted for this, but doesn't appear to work.

about = about.replace(/\[url=([^\s\]]+)\s*\](.*(?=\[\/url\]))\[\/url\]/g, '$2')

Body:
I worked it out with the following:

about = about.replace(/\[url=([^\]]+)\](.*?)\[\/url\]/gi, "<a href=\"$1\" target=\"_blank\">$2</a>")


问:
How to compile and run C++ with MinGW using Eclipse and CDT?
I would like to do some C++ development on Windows using Eclipse and the CDT plugin. I use Eclipse Helios SR1 and have installed the CDT plugin. I have also installed MinGW and now I wrote a simple "Hello World" in Eclipse.

hello.cpp

```<code>#include <iostream>
using namespace std;
int main()
{
    cout << "Hello World" << endl;
    return 0;
}
</code>```

In Eclipse using the CDT plugin and the MinGW compiler. How can I compile my program? And how can I test run the program from within Eclipse?

答:
Chocolatey is one package manager that allows mingw install with a single command using Windows Powershell.

```<code>choco install mingw --version=8.1.0
</code>```

After the installation is done, add the below toolchain path to Eclipse->Window->Preferences-> Core Build ToolChains -> User Defined ToolChains.

```<code>C:\ProgramData\chocolatey\lib\mingw\tools\install\mingw64\bin\gcc.exe
</code>```

Restart eclipse.
The MinGW toolchain should be available for use now in Eclipse.

Body:
I would like to do some C++ development on Windows using Eclipse and the CDT plugin. I use Eclipse Helios SR1 and have installed the CDT plugin. I have also installed MinGW and now I wrote a simple "Hello World" in Eclipse.

hello.cpp

#include <iostream>
using namespace std;
int main()
{
    cout << "Hello World" << endl;
    return 0;
}

In Eclipse using the CDT plugin and the MinGW compiler. How can I compile my program? And how can I test run the program from within Eclipse?

Body:
Chocolatey is one package manager that allows mingw install with a single command using Windows Powershell.

choco install mingw --version=8.1.0

After the installation is done, add the below toolchain path to Eclipse->Window->Preferences-> Core Build ToolChains -> User Defined ToolChains.

C:\ProgramData\chocolatey\lib\mingw\tools\install\mingw64\bin\gcc.exe

Restart eclipse.
The MinGW toolchain should be available for use now in Eclipse.


问:
Create a channel with discord.js
I am trying to do a discord bot that creates channels among others, but I can't achieve it because my code it's supposed to create a channel but... I tried a lot of things, these are the two that haven't given me error: (I substituted the bot's token with DONOTLOOK, I won't have problems...)

OPTION 1:

```<code>const Discord = require('discord.js');
const bot = new Discord.Client();

bot.login('DONOTLOOK');

bot.on('ready', () => {
  console.log('Logged in as ${bot.user.tag}!');
});

bot.on('message', msg => {
  if (msg.content === 'ping') {
    msg.reply('Pong!');
    var server = msg.guild;
    bot.channels.add("anewchannel", {type: 0});
  }
});
</code>```

OPTION 2:

```<code>const Discord = require('discord.js');
const bot = new Discord.Client();

bot.login('DONOTLOOK');

bot.on('ready', () => {
  console.log(`Logged in as ${bot.user.tag}!`);
});

bot.on('message', msg => {
  if (msg.content === 'ping') {
    msg.reply('Pong!');
    var server = msg.guild;
    const channel = bot.channels.add("newchannel", {type: 0});
  }
});
</code>```

That don't gave me any node.js error on console, the bot answered me but haven't created the channel. I also looked two references(https://discord.com/developers/docs/resources/guild#create-guild-channel, https://discord.js.org/#/docs/main/stable/class/GuildChannelManager?scrollTo=create), no one's solutions worked, the discord.com one gave me node.js error too. The two options above are taken from the discord.js file, they gave no node.js errors but doesn't create the channel. If someone can help me please.

答:
If you don't want to use messages to create you can use..</p>
```<code>var bot = client.guilds.cache.get("<GUILD-ID>");
  server.channels.create("<CHANNEL-TEXT>", "<CHANNEL-TYPE>").then(channel => {
    var cat = server.channels.cache.find(c => c.name == "BUSINESSES" && c.type == "category");
    if (!cat) { console.log("category does not exist"); return; }
    channel.setParent(cat.id);
  })
</code>```

Title: Create a channel with discord.js

Body:
I am trying to do a discord bot that creates channels among others, but I can't achieve it because my code it's supposed to create a channel but... I tried a lot of things, these are the two that haven't given me error: (I substituted the bot's token with DONOTLOOK, I won't have problems...)

OPTION 1:

const Discord = require('discord.js');
const bot = new Discord.Client();

bot.login('DONOTLOOK');

bot.on('ready', () => {
  console.log('Logged in as ${bot.user.tag}!');
});

bot.on('message', msg => {
  if (msg.content === 'ping') {
    msg.reply('Pong!');
    var server = msg.guild;
    bot.channels.add("anewchannel", {type: 0});
  }
});

OPTION 2:

const Discord = require('discord.js');
const bot = new Discord.Client();

bot.login('DONOTLOOK');

bot.on('ready', () => {
  console.log(`Logged in as ${bot.user.tag}!`);
});

bot.on('message', msg => {
  if (msg.content === 'ping') {
    msg.reply('Pong!');
    var server = msg.guild;
    const channel = bot.channels.add("newchannel", {type: 0});
  }
});

That don't gave me any node.js error on console, the bot answered me but haven't created the channel. I also looked two references(https://discord.com/developers/docs/resources/guild#create-guild-channel, https://discord.js.org/#/docs/main/stable/class/GuildChannelManager?scrollTo=create), no one's solutions worked, the discord.com one gave me node.js error too. The two options above are taken from the discord.js file, they gave no node.js errors but doesn't create the channel. If someone can help me please.

Body:
If you don't want to use messages to create you can use..

var bot = client.guilds.cache.get("<GUILD-ID>");
  server.channels.create("<CHANNEL-TEXT>", "<CHANNEL-TYPE>").then(channel => {
    var cat = server.channels.cache.find(c => c.name == "BUSINESSES" && c.type == "category");
    if (!cat) { console.log("category does not exist"); return; }
    channel.setParent(cat.id);
  })


问:
Split discount (coupon) row into multiple deducted cost rows in WooCommerce order totals table
If there are 2 discount coupons used, it shows the sum of 2 coupons in the Woocommerce order totals table, while I want to show the deducted cost of each coupon separately.

For example, 2 coupons are inserted, currently it shows:

coupon : $100

I want to change this to:

coupon1(coupon code) : $50

coupon2(coupon code) : $50

Path from the WooCommerce template file: order-details.php

foreach ( $order->get_order_item_totals() as $key => $total ) {
    ?>

            <?php echo esc_html( $total['label'] ); ?>
            <?php echo ( 'payment_method' === $key ) ? esc_html( $total['value'] ) : wp_kses_post( $total['value'] ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>

        <?php
}
```

Any advice on how to change this?

答:
It is not necessary to add HTML table tags via the woocommerce_get_order_item_totals hook, since it concerns table rows.

Next answer removes the default discount row and splits it over several rows with the desired details.

Functions used in this answer:

WC_Abstract_Order::get_coupon_codes()

get_discount()

get_code()

So you get:

function filter_woocommerce_get_order_item_totals( $total_rows, $order, $tax_display ) {
    // Exit if there is no coupons applied
    if ( sizeof ( $order->get_coupon_codes() ) == 0 ) return $total_rows;

    // Initializing
    $new_rows = [];

    // Loop through order total lines
    foreach ( $total_rows as $total_key => $total_row ) {
        // Store current rows, except discount
        if ( $total_key != 'discount' ) {
            // Store
            $new_rows[$total_key] = $total_row;
        } else {
            // For each coupon
            foreach ( $order->get_items('coupon') as $coupon ) {
                // New rows
                $new_rows[$coupon->get_code()] = array(
                    'label' => __( 'Coupon: ', 'woocommerce' ) . $coupon->get_code(),
                    'value' => wc_price( $coupon->get_discount() ),
                );
            }
        }
    }

    // Overwrite
    $total_rows = $new_rows;

    return $total_rows;
}
add_filter( 'woocommerce_get_order_item_totals', 'filter_woocommerce_get_order_item_totals', 10, 3 );
```

Result:

Related: Add coupon names and percentage to WooCommerce view order details and email notifications

Body:
If there are 2 discount coupons used, it shows the sum of 2 coupons in the Woocommerce order totals table, while I want to show the deducted cost of each coupon separately.

For example, 2 coupons are inserted, currently it shows:

coupon : $100

I want to change this to:

coupon1(coupon code) : $50

coupon2(coupon code) : $50

Path from the WooCommerce template file: order-details.php

foreach ( $order->get_order_item_totals() as $key => $total ) {
    ?>

            <?php echo esc_html( $total['label'] ); ?>
            <?php echo ( 'payment_method' === $key ) ? esc_html( $total['value'] ) : wp_kses_post( $total['value'] ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>

        <?php
}

Any advice on how to change this?

Body:
It is not necessary to add HTML table tags via the woocommerce_get_order_item_totals hook, since it concerns table rows.

Next answer removes the default discount row and splits it over several rows with the desired details.

Functions used in this answer:

WC_Abstract_Order::get_coupon_codes()

get_discount()

get_code()

So you get:

function filter_woocommerce_get_order_item_totals( $total_rows, $order, $tax_display ) {
    // Exit if there is no coupons applied
    if ( sizeof ( $order->get_coupon_codes() ) == 0 ) return $total_rows;

    // Initializing
    $new_rows = [];

    // Loop through order total lines
    foreach ( $total_rows as $total_key => $total_row ) {
        // Store current rows, except discount
        if ( $total_key != 'discount' ) {
            // Store
            $new_rows[$total_key] = $total_row;
        } else {
            // For each coupon
            foreach ( $order->get_items('coupon') as $coupon ) {
                // New rows
                $new_rows[$coupon->get_code()] = array(
                    'label' => __( 'Coupon: ', 'woocommerce' ) . $coupon->get_code(),
                    'value' => wc_price( $coupon->get_discount() ),
                );
            }
        }
    }

    // Overwrite
    $total_rows = $new_rows;

    return $total_rows;
}
add_filter( 'woocommerce_get_order_item_totals', 'filter_woocommerce_get_order_item_totals', 10, 3 );

Result:

Related: Add coupon names and percentage to WooCommerce view order details and email notifications