问:
java.io.IOException: unable to create directory: /storage/emulated/0/tokens
I'm trying to hook my Android application up to Google Calendars. I've followed the quick start tutorial, have asked the user for permission to write to external storage, yet I cannot get the code to run without throwing a java.io.IOException.

My code looks like this:

GoogleCalendarModule.kt

```<code>class GoogleCalendarModule {
    var APPLICATION_NAME: String = "Conglobo"
    var JSON_FACTORY: JacksonFactory = JacksonFactory.getDefaultInstance()
    var TOKENS_DIRECTORY_PATH: String = "./tokens"

    var SCOPES: List<String> = Collections.singletonList(CalendarScopes.CALENDAR_READONLY)
    private var CREDENTIALS_FILE_PATH: String = "/credentials.json"

    fun getCredentials(HTTP_TRANSPORT: NetHttpTransport): com.google.api.client.auth.oauth2.Credential? {

        val inputStream: InputStream = this.javaClass.getResourceAsStream(CREDENTIALS_FILE_PATH)
            ?: throw FileNotFoundException("Resource Not found: $CREDENTIALS_FILE_PATH")

        val clientSecrets: GoogleClientSecrets = GoogleClientSecrets.load(JSON_FACTORY, InputStreamReader(inputStream))

        val tokenFolder = File(getExternalStorageDirectory(), File.separator.toString() + TOKENS_DIRECTORY_PATH)
        if (!tokenFolder.exists()) {
            tokenFolder.mkdirs()
        }

        val flow: GoogleAuthorizationCodeFlow = GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(FileDataStoreFactory(tokenFolder))
            .setAccessType("offline")
            .build();

        val receiver: LocalServerReceiver = LocalServerReceiver.Builder().setPort(8888).build()

        return AuthorizationCodeInstalledApp(flow, receiver).authorize("user")
    }

    fun doSomething() {
        val HTTP_TRANSPORT = NetHttpTransport()
        val service: Calendar = Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build()

        val now = DateTime(System.currentTimeMillis())
        val events: Events = service.events().list("primary")
            .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute()

        val items: List<Event> = events.items
        if (items.isEmpty()) {
            println("No events")
        } else {
            println("Upcoming events")
            for(event: Event in items) {
                var start: DateTime = event.start.dateTime
                if(start == null) {
                    start = event.start.date
                }

                print(event.summary)
            }
        }
    }
}
</code>```

Then I check against current permissions in the MainActivity

MainActivity.kt

```<code>class MainActivity: AppCompatActivity(), ITeamFragmentDelegate {

    @Inject
    lateinit var teamInfoModule: TeamInfoModule;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
                print("Permission is granted");
            } else {

                print("Permission is revoked");
                ActivityCompat.requestPermissions(this, Array<String>(1) { Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }

        GoogleCalendarModule().doSomething()

        setContentView(R.layout.activity_main)
        DaggerServiceModuleComponent.create().inject(this)

        val teamArrayList: ArrayList<Team> = this.teamInfoModule.getAllTeamData()

        for(team: Team in teamArrayList) {
            val bundle = Bundle()
            val teamFragment = TeamFragment()

            bundle.putParcelable("teamData", team)
            teamFragment.arguments = bundle

            supportFragmentManager.beginTransaction()
                .add(R.id.root_container, teamFragment)
                .commitAllowingStateLoss()
        }
    }

    override fun onTeamClicked(fragment: TeamFragment, team: Team) {
        val intent = Intent(this, ViewTeamBacklogActivity::class.java)
        intent.putExtra("teamId", team.id)
        startActivity(intent)
    }
}
</code>```

And I even have the permissions declared in AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bluelightlite">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ViewTeamBacklogActivity">

        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

I've searched around S.O and it appears to be a common problem but none of the solutions I've found have worked. Could someone please help?

答:
Found the problem.

As of Android SDK 23 and onwards (I believe). Refactoring GoogleCalendarModule.kt to this:

```<code>package com.example.bluelightlite.modules

import android.content.Context
import com.example.bluelightlite.constants.APPLICATION_NAME
import com.example.bluelightlite.constants.JSON_FACTORY
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.util.DateTime
import com.google.api.services.calendar.Calendar
import com.google.api.services.calendar.model.Event
import com.google.api.services.calendar.model.Events

class GoogleCalendarsServiceModule constructor(context: Context) {

    private val googleCredentialsUtilityModule = GoogleCredentialsUtilityModule(context)

    fun getEvents(): List<Event> {

        val httpTransport = NetHttpTransport()
        val service: Calendar = Calendar.Builder(httpTransport, JSON_FACTORY, this.googleCredentialsUtilityModule.getCredentials(httpTransport))
            .setApplicationName(APPLICATION_NAME)
            .build()

        val now = DateTime(System.currentTimeMillis())
        val events: Events = service.events().list("primary")
            .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute()

        return events.items;
    }
}
</code>```

And creating a GoogleCredentialsUtilityModule.kt file that looks like this:

```<code>package com.example.bluelightlite.modules

import android.content.Context
import com.example.bluelightlite.constants.CREDENTIALS_FILE_PATH
import com.example.bluelightlite.constants.JSON_FACTORY
import com.example.bluelightlite.constants.SCOPES
import com.example.bluelightlite.constants.TOKENS_DIRECTORY_PATH
import com.google.api.client.auth.oauth2.Credential
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.util.store.FileDataStoreFactory
import java.io.File
import java.io.FileNotFoundException
import java.io.InputStream
import java.io.InputStreamReader

class GoogleCredentialsUtilityModule constructor(private val context: Context) {

    /**
     * Creates an authorized Credential object.
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws java.io.IOException If the credentials.json file cannot be found.
     */
    fun getCredentials(HTTP_TRANSPORT: NetHttpTransport): Credential {

        val inputStream: InputStream = getCredentialsAsInputStream()
        val clientSecrets: GoogleClientSecrets = GoogleClientSecrets.load(JSON_FACTORY, InputStreamReader(inputStream))

        createTokenFolderIfMissing()

        val authorisationFlow: GoogleAuthorizationCodeFlow = getAuthorisationFlow(HTTP_TRANSPORT, clientSecrets)
        val receiver: LocalServerReceiver = LocalServerReceiver.Builder().setPort(8888).build()

        return AuthorizationCodeInstalledApp(authorisationFlow, receiver).authorize("freeman.marc880@gmail.com")
    }

    private fun getCredentialsAsInputStream(): InputStream {
        return this.javaClass.getResourceAsStream(CREDENTIALS_FILE_PATH)
            ?: throw FileNotFoundException("Resource Not found: $CREDENTIALS_FILE_PATH")
    }

    private fun createTokenFolderIfMissing() {
        val tokenFolder = getTokenFolder()
        if (!tokenFolder.exists()) {
            tokenFolder.mkdir()
        }
    }

    private fun getTokenFolder(): File {
        return File(this.context.getExternalFilesDir("")?.absolutePath + TOKENS_DIRECTORY_PATH)
    }

    private fun getAuthorisationFlow(HTTP_TRANSPORT: NetHttpTransport, clientSecrets: GoogleClientSecrets): GoogleAuthorizationCodeFlow {
        return GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(FileDataStoreFactory(getTokenFolder()))
            .setAccessType("offline")
            .build()
    }
}
</code>```

makes it work.

What I did was pass the context down into the Google Credentials Module and asked it to get the external storage directory from the current context on this line of code:

```<code>  private fun getTokenFolder(): File {
        return File(this.context.getExternalFilesDir("")?.absolutePath + TOKENS_DIRECTORY_PATH)
    }
</code>```

Body:
I'm trying to hook my Android application up to Google Calendars. I've followed the quick start tutorial, have asked the user for permission to write to external storage, yet I cannot get the code to run without throwing a java.io.IOException.

My code looks like this:

GoogleCalendarModule.kt

class GoogleCalendarModule {
    var APPLICATION_NAME: String = "Conglobo"
    var JSON_FACTORY: JacksonFactory = JacksonFactory.getDefaultInstance()
    var TOKENS_DIRECTORY_PATH: String = "./tokens"

    var SCOPES: List<String> = Collections.singletonList(CalendarScopes.CALENDAR_READONLY)
    private var CREDENTIALS_FILE_PATH: String = "/credentials.json"

    fun getCredentials(HTTP_TRANSPORT: NetHttpTransport): com.google.api.client.auth.oauth2.Credential? {

        val inputStream: InputStream = this.javaClass.getResourceAsStream(CREDENTIALS_FILE_PATH)
            ?: throw FileNotFoundException("Resource Not found: $CREDENTIALS_FILE_PATH")

        val clientSecrets: GoogleClientSecrets = GoogleClientSecrets.load(JSON_FACTORY, InputStreamReader(inputStream))

        val tokenFolder = File(getExternalStorageDirectory(), File.separator.toString() + TOKENS_DIRECTORY_PATH)
        if (!tokenFolder.exists()) {
            tokenFolder.mkdirs()
        }

        val flow: GoogleAuthorizationCodeFlow = GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(FileDataStoreFactory(tokenFolder))
            .setAccessType("offline")
            .build();

        val receiver: LocalServerReceiver = LocalServerReceiver.Builder().setPort(8888).build()

        return AuthorizationCodeInstalledApp(flow, receiver).authorize("user")
    }

    fun doSomething() {
        val HTTP_TRANSPORT = NetHttpTransport()
        val service: Calendar = Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build()

        val now = DateTime(System.currentTimeMillis())
        val events: Events = service.events().list("primary")
            .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute()

        val items: List<Event> = events.items
        if (items.isEmpty()) {
            println("No events")
        } else {
            println("Upcoming events")
            for(event: Event in items) {
                var start: DateTime = event.start.dateTime
                if(start == null) {
                    start = event.start.date
                }

                print(event.summary)
            }
        }
    }
}

Then I check against current permissions in the MainActivity

MainActivity.kt

class MainActivity: AppCompatActivity(), ITeamFragmentDelegate {

    @Inject
    lateinit var teamInfoModule: TeamInfoModule;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
                print("Permission is granted");
            } else {

                print("Permission is revoked");
                ActivityCompat.requestPermissions(this, Array<String>(1) { Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }

        GoogleCalendarModule().doSomething()

        setContentView(R.layout.activity_main)
        DaggerServiceModuleComponent.create().inject(this)

        val teamArrayList: ArrayList<Team> = this.teamInfoModule.getAllTeamData()

        for(team: Team in teamArrayList) {
            val bundle = Bundle()
            val teamFragment = TeamFragment()

            bundle.putParcelable("teamData", team)
            teamFragment.arguments = bundle

            supportFragmentManager.beginTransaction()
                .add(R.id.root_container, teamFragment)
                .commitAllowingStateLoss()
        }
    }

    override fun onTeamClicked(fragment: TeamFragment, team: Team) {
        val intent = Intent(this, ViewTeamBacklogActivity::class.java)
        intent.putExtra("teamId", team.id)
        startActivity(intent)
    }
}

And I even have the permissions declared in AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bluelightlite">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ViewTeamBacklogActivity">

        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I've searched around S.O and it appears to be a common problem but none of the solutions I've found have worked. Could someone please help?

Body:
Found the problem.

As of Android SDK 23 and onwards (I believe). Refactoring GoogleCalendarModule.kt to this:

package com.example.bluelightlite.modules

import android.content.Context
import com.example.bluelightlite.constants.APPLICATION_NAME
import com.example.bluelightlite.constants.JSON_FACTORY
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.util.DateTime
import com.google.api.services.calendar.Calendar
import com.google.api.services.calendar.model.Event
import com.google.api.services.calendar.model.Events

class GoogleCalendarsServiceModule constructor(context: Context) {

    private val googleCredentialsUtilityModule = GoogleCredentialsUtilityModule(context)

    fun getEvents(): List<Event> {

        val httpTransport = NetHttpTransport()
        val service: Calendar = Calendar.Builder(httpTransport, JSON_FACTORY, this.googleCredentialsUtilityModule.getCredentials(httpTransport))
            .setApplicationName(APPLICATION_NAME)
            .build()

        val now = DateTime(System.currentTimeMillis())
        val events: Events = service.events().list("primary")
            .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute()

        return events.items;
    }
}

And creating a GoogleCredentialsUtilityModule.kt file that looks like this:

package com.example.bluelightlite.modules

import android.content.Context
import com.example.bluelightlite.constants.CREDENTIALS_FILE_PATH
import com.example.bluelightlite.constants.JSON_FACTORY
import com.example.bluelightlite.constants.SCOPES
import com.example.bluelightlite.constants.TOKENS_DIRECTORY_PATH
import com.google.api.client.auth.oauth2.Credential
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.util.store.FileDataStoreFactory
import java.io.File
import java.io.FileNotFoundException
import java.io.InputStream
import java.io.InputStreamReader

class GoogleCredentialsUtilityModule constructor(private val context: Context) {

    /**
     * Creates an authorized Credential object.
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws java.io.IOException If the credentials.json file cannot be found.
     */
    fun getCredentials(HTTP_TRANSPORT: NetHttpTransport): Credential {

        val inputStream: InputStream = getCredentialsAsInputStream()
        val clientSecrets: GoogleClientSecrets = GoogleClientSecrets.load(JSON_FACTORY, InputStreamReader(inputStream))

        createTokenFolderIfMissing()

        val authorisationFlow: GoogleAuthorizationCodeFlow = getAuthorisationFlow(HTTP_TRANSPORT, clientSecrets)
        val receiver: LocalServerReceiver = LocalServerReceiver.Builder().setPort(8888).build()

        return AuthorizationCodeInstalledApp(authorisationFlow, receiver).authorize("freeman.marc880@gmail.com")
    }

    private fun getCredentialsAsInputStream(): InputStream {
        return this.javaClass.getResourceAsStream(CREDENTIALS_FILE_PATH)
            ?: throw FileNotFoundException("Resource Not found: $CREDENTIALS_FILE_PATH")
    }

    private fun createTokenFolderIfMissing() {
        val tokenFolder = getTokenFolder()
        if (!tokenFolder.exists()) {
            tokenFolder.mkdir()
        }
    }

    private fun getTokenFolder(): File {
        return File(this.context.getExternalFilesDir("")?.absolutePath + TOKENS_DIRECTORY_PATH)
    }

    private fun getAuthorisationFlow(HTTP_TRANSPORT: NetHttpTransport, clientSecrets: GoogleClientSecrets): GoogleAuthorizationCodeFlow {
        return GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(FileDataStoreFactory(getTokenFolder()))
            .setAccessType("offline")
            .build()
    }
}

makes it work.

What I did was pass the context down into the Google Credentials Module and asked it to get the external storage directory from the current context on this line of code:

  private fun getTokenFolder(): File {
        return File(this.context.getExternalFilesDir("")?.absolutePath + TOKENS_DIRECTORY_PATH)
    }


来源: stackexchange

问:
React Native app keeps closing on android emulator
I'm trying to run a react native app on the android emulator (react-native run-android), however it keeps crashing with the error message "MYAPP has stopped". I'm trying to figure out where I can debug this further (error messages, logs, etc). I don't exactly see any error messages on the terminal nor on the emulator itself. So besides trying to resolve why the app won't deploy ... where does one look to further debug app deployment issues on an android emulator?

Side note: I upgraded from version 0.31.0 to 0.32.0 and ran the react-native upgrade command, which also required that some files be over-written (I chose the option to overwrite all files). Should I be worried that the latest changes from upgrade to 0.32.0 are not working or incomplete? Any steps I can take to verify that the latest changes are there?

Update: I created a new sample react native project just to see if there was something wrong with RN's latest version. It worked fine. Then took the sample code in index.android.js and overwrote it in my project's index.android.js and re-ran. Still getting the same issue with trying to deploy it to an Android emulator. Removed the node_modules directory, reran, still same issue. I'm now thinking this has something to do with the upgrade process... this is very frustrating.

Update v2: Thanks to @GabeSechan for the hint and direction, here's the stack trace that I found:

```<code>09-04 03:24:41.297  5008  5008 E AndroidRuntime: FATAL EXCEPTION: main
09-04 03:24:41.297  5008  5008 E AndroidRuntime: Process: com.helpr, PID: 5008
09-04 03:24:41.297  5008  5008 E AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.helpr/com.helpr.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.facebook.react.ReactApplication
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.ActivityThread.-wrap12(ActivityThread.java)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:102)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:154)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.ActivityThread.main(ActivityThread.java:6077)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Native Method)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
09-04 03:24:41.297  5008  5008 E AndroidRuntime: Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.facebook.react.ReactApplication
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at com.facebook.react.ReactActivity.getUseDeveloperSupport(ReactActivity.java:89)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at com.facebook.react.ReactActivity.onCreate(ReactActivity.java:96)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.Activity.performCreate(Activity.java:6664)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    ... 9 more
</code>```

After a quick google search, it seems this is an existing issue when it comes to upgrading React Native. I'll post an answer, answering my own question.

答:
To solve your problem, add these two lines in android\app\build.gradle file under dependencies`:

```<code>implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to run a react native app on the android emulator (react-native run-android), however it keeps crashing with the error message "MYAPP has stopped". I'm trying to figure out where I can debug this further (error messages, logs, etc). I don't exactly see any error messages on the terminal nor on the emulator itself. So besides trying to resolve why the app won't deploy ... where does one look to further debug app deployment issues on an android emulator?

Side note: I upgraded from version 0.31.0 to 0.32.0 and ran the react-native upgrade command, which also required that some files be over-written (I chose the option to overwrite all files). Should I be worried that the latest changes from upgrade to 0.32.0 are not working or incomplete? Any steps I can take to verify that the latest changes are there?

Update: I created a new sample react native project just to see if there was something wrong with RN's latest version. It worked fine. Then took the sample code in index.android.js and overwrote it in my project's index.android.js and re-ran. Still getting the same issue with trying to deploy it to an Android emulator. Removed the node_modules directory, reran, still same issue. I'm now thinking this has something to do with the upgrade process... this is very frustrating.

Update v2: Thanks to @GabeSechan for the hint and direction, here's the stack trace that I found:

09-04 03:24:41.297  5008  5008 E AndroidRuntime: FATAL EXCEPTION: main
09-04 03:24:41.297  5008  5008 E AndroidRuntime: Process: com.helpr, PID: 5008
09-04 03:24:41.297  5008  5008 E AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.helpr/com.helpr.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.facebook.react.ReactApplication
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.ActivityThread.-wrap12(ActivityThread.java)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:102)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:154)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.ActivityThread.main(ActivityThread.java:6077)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Native Method)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
09-04 03:24:41.297  5008  5008 E AndroidRuntime: Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.facebook.react.ReactApplication
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at com.facebook.react.ReactActivity.getUseDeveloperSupport(ReactActivity.java:89)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at com.facebook.react.ReactActivity.onCreate(ReactActivity.java:96)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.Activity.performCreate(Activity.java:6664)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
09-04 03:24:41.297  5008  5008 E AndroidRuntime:    ... 9 more

After a quick google search, it seems this is an existing issue when it comes to upgrading React Native. I'll post an answer, answering my own question.

Body:
To solve your problem, add these two lines in android\app\build.gradle file under dependencies`:

implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02'

ContentLicense: CC BY-SA 4.0


问:
Cannot implicity return type void in generic class?
I'm trying to build a simple generic class which should take an object and a delegate as generic parameters.I receive the following error when I bind a method to a event:

Cannot implicitly convert type 'void' to 'ConsoleApp3.test.Del'

I do not understand why I receive this error as my delegate returns void and the method attached to the event also returns void.

This is the code:

```<code>interface ITerminable
    {
        int Param_1 { get; set; }
    }

    class test<T,F> where T:ITerminable,new()
                    where F : Delegate,new()
    {

        internal delegate void Del();
        internal static event Del Ev_fire;

        static T a = new T();
        static F b = new F();

        public static void InvokeEvent()
        {
            Console.WriteLine("Value not added !");

        }

        public static void Validate()
        {
            if (a.Param_1 < 0.5)
            {
                Console.WriteLine("Value Added");
                b.DynamicInvoke();
            }
            else
            {
                Ev_fire += InvokeEvent();

                Ev_fire?.Invoke();
            }
        }

    }
</code>```

The error is at line : Ev_fire += InvokeEvent();

答: try this: Ev_fire += InvokeEvent;

Body:
I'm trying to build a simple generic class which should take an object and a delegate as generic parameters.I receive the following error when I bind a method to a event:

Cannot implicitly convert type 'void' to 'ConsoleApp3.test.Del'

I do not understand why I receive this error as my delegate returns void and the method attached to the event also returns void.

This is the code:

interface ITerminable
    {
        int Param_1 { get; set; }
    }

    class test<T,F> where T:ITerminable,new()
                    where F : Delegate,new()
    {

        internal delegate void Del();
        internal static event Del Ev_fire;

        static T a = new T();
        static F b = new F();

        public static void InvokeEvent()
        {
            Console.WriteLine("Value not added !");

        }

        public static void Validate()
        {
            if (a.Param_1 < 0.5)
            {
                Console.WriteLine("Value Added");
                b.DynamicInvoke();
            }
            else
            {
                Ev_fire += InvokeEvent();

                Ev_fire?.Invoke();
            }
        }

    }

The error is at line : Ev_fire += InvokeEvent();

Body: try this: Ev_fire += InvokeEvent;


问:
How to Increment count based on condition
I'm trying to extract a new column based on a condition so the new column will act as a counter and it will just count if (MessageDate1- MessageDate2).TotalMinutes > 10.

For example if i've the following input:

```<code>╔════════════════╦═══════════════════════╦═══════════════════════╗
║ ConversationId ║     MessageDate1      ║     MessageDate2      ║
╠════════════════╬═══════════════════════╬═══════════════════════╣
║              1 ║ 2/15/2012 11:53:16 AM ║ 1/1/0001 12:00:00 AM  ║
║              1 ║ 2/16/2012 11:53:20 AM ║ 2/15/2012 11:53:16 AM ║
║              1 ║ 2/16/2012 11:54:01 AM ║ 2/16/2012 11:53:20 AM ║
║              1 ║ 2/16/2012 11:05:03 PM ║ 2/16/2012 11:54:01 AM ║
║              1 ║ 2/16/2012 11:09:03 PM ║ 2/16/2012 11:05:03 PM ║
║              1 ║ 2/16/2012 11:11:03 PM ║ 2/16/2012 11:09:03 PM ║
║              1 ║ 2/16/2012 11:11:04 PM ║ 2/16/2012 11:11:03 PM ║
║              1 ║ 2/16/2012 11:11:05 PM ║ 2/16/2012 11:11:04 PM ║
║              1 ║ 2/16/2012 11:22:06 PM ║ 2/16/2012 11:11:05 PM ║
║              1 ║ 2/17/2012 11:05:03 PM ║ 2/16/2012 11:22:06 PM ║
║              1 ║ 2/17/2012 11:09:03 PM ║ 2/17/2012 11:05:03 PM ║
║              1 ║ 2/17/2012 11:11:03 PM ║ 2/17/2012 11:09:03 PM ║
║              2 ║ 2/15/2012 11:53:18 AM ║ 1/1/0001 12:00:00 AM  ║
║              2 ║ 2/16/2012 11:54:01 AM ║ 2/15/2012 11:53:18 AM ║
║              2 ║ 2/16/2012 11:54:02 AM ║ 2/16/2012 11:54:01 AM ║
║              3 ║ 2/16/2012 11:53:50 AM ║ 1/1/0001 12:00:00 AM  ║
║              3 ║ 2/16/2012 11:54:50 AM ║ 2/16/2012 11:53:50 AM ║
║              4 ║ 2/16/2012 11:54:04 AM ║ 1/1/0001 12:00:00 AM  ║
╚════════════════╩═══════════════════════╩═══════════════════════╝
</code>```

So the output would be:

```<code>╔════════════════╦═══════════════════════╦═══════════════════════╦═════════╗
║ ConversationID ║     MessageDate1      ║     MessageDate2      ║ Counter ║
╠════════════════╬═══════════════════════╬═══════════════════════╬═════════╣
║              1 ║ 2/15/2012 11:53:16 AM ║ 1/1/0001 12:00:00 AM  ║       1 ║
║              1 ║ 2/16/2012 11:53:20 AM ║ 2/15/2012 11:53:16 AM ║       2 ║
║              1 ║ 2/16/2012 11:54:01 AM ║ 2/16/2012 11:53:20 AM ║       2 ║
║              1 ║ 2/16/2012 11:05:03 PM ║ 2/16/2012 11:54:01 AM ║       3 ║
║              1 ║ 2/16/2012 11:09:03 PM ║ 2/16/2012 11:05:03 PM ║       3 ║
║              1 ║ 2/16/2012 11:11:03 PM ║ 2/16/2012 11:09:03 PM ║       3 ║
║              1 ║ 2/16/2012 11:11:04 PM ║ 2/16/2012 11:11:03 PM ║       3 ║
║              1 ║ 2/16/2012 11:11:05 PM ║ 2/16/2012 11:11:04 PM ║       3 ║
║              1 ║ 2/16/2012 11:22:06 PM ║ 2/16/2012 11:11:05 PM ║       4 ║
║              1 ║ 2/17/2012 11:05:03 PM ║ 2/16/2012 11:22:06 PM ║       5 ║
║              1 ║ 2/17/2012 11:09:03 PM ║ 2/17/2012 11:05:03 PM ║       5 ║
║              1 ║ 2/17/2012 11:11:03 PM ║ 2/17/2012 11:09:03 PM ║       5 ║
║              2 ║ 2/15/2012 11:53:18 AM ║ 1/1/0001 12:00:00 AM  ║       6 ║
║              2 ║ 2/16/2012 11:54:01 AM ║ 2/15/2012 11:53:18 AM ║       7 ║
║              2 ║ 2/16/2012 11:54:02 AM ║ 2/16/2012 11:54:01 AM ║       7 ║
║              3 ║ 2/16/2012 11:53:50 AM ║ 1/1/0001 12:00:00 AM  ║       8 ║
║              3 ║ 2/16/2012 11:54:50 AM ║ 2/16/2012 11:53:50 AM ║       8 ║
║              4 ║ 2/16/2012 11:54:04 AM ║ 1/1/0001 12:00:00 AM  ║       9 ║
╚════════════════╩═══════════════════════╩═══════════════════════╩═════════╝
</code>```

Body:
I'm trying to extract a new column based on a condition so the new column will act as a counter and it will just count if (MessageDate1- MessageDate2).TotalMinutes > 10.

For example if i've the following input:

╔════════════════╦═══════════════════════╦═══════════════════════╗
║ ConversationId ║     MessageDate1      ║     MessageDate2      ║
╠════════════════╬═══════════════════════╬═══════════════════════╣
║              1 ║ 2/15/2012 11:53:16 AM ║ 1/1/0001 12:00:00 AM  ║
║              1 ║ 2/16/2012 11:53:20 AM ║ 2/15/2012 11:53:16 AM ║
║              1 ║ 2/16/2012 11:54:01 AM ║ 2/16/2012 11:53:20 AM ║
║              1 ║ 2/16/2012 11:05:03 PM ║ 2/16/2012 11:54:01 AM ║
║              1 ║ 2/16/2012 11:09:03 PM ║ 2/16/2012 11:05:03 PM ║
║              1 ║ 2/16/2012 11:11:03 PM ║ 2/16/2012 11:09:03 PM ║
║              1 ║ 2/16/2012 11:11:04 PM ║ 2/16/2012 11:11:03 PM ║
║              1 ║ 2/16/2012 11:11:05 PM ║ 2/16/2012 11:11:04 PM ║
║              1 ║ 2/16/2012 11:22:06 PM ║ 2/16/2012 11:11:05 PM ║
║              1 ║ 2/17/2012 11:05:03 PM ║ 2/16/2012 11:22:06 PM ║
║              1 ║ 2/17/2012 11:09:03 PM ║ 2/17/2012 11:05:03 PM ║
║              1 ║ 2/17/2012 11:11:03 PM ║ 2/17/2012 11:09:03 PM ║
║              2 ║ 2/15/2012 11:53:18 AM ║ 1/1/0001 12:00:00 AM  ║
║              2 ║ 2/16/2012 11:54:01 AM ║ 2/15/2012 11:53:18 AM ║
║              2 ║ 2/16/2012 11:54:02 AM ║ 2/16/2012 11:54:01 AM ║
║              3 ║ 2/16/2012 11:53:50 AM ║ 1/1/0001 12:00:00 AM  ║
║              3 ║ 2/16/2012 11:54:50 AM ║ 2/16/2012 11:53:50 AM ║
║              4 ║ 2/16/2012 11:54:04 AM ║ 1/1/0001 12:00:00 AM  ║
╚════════════════╩═══════════════════════╩═══════════════════════╝

So the output would be:

╔════════════════╦═══════════════════════╦═══════════════════════╦═════════╗
║ ConversationID ║     MessageDate1      ║     MessageDate2      ║ Counter ║
╠════════════════╬═══════════════════════╬═══════════════════════╬═════════╣
║              1 ║ 2/15/2012 11:53:16 AM ║ 1/1/0001 12:00:00 AM  ║       1 ║
║              1 ║ 2/16/2012 11:53:20 AM ║ 2/15/2012 11:53:16 AM ║       2 ║
║              1 ║ 2/16/2012 11:54:01 AM ║ 2/16/2012 11:53:20 AM ║       2 ║
║              1 ║ 2/16/2012 11:05:03 PM ║ 2/16/2012 11:54:01 AM ║       3 ║
║              1 ║ 2/16/2012 11:09:03 PM ║ 2/16/2012 11:05:03 PM ║       3 ║
║              1 ║ 2/16/2012 11:11:03 PM ║ 2/16/2012 11:09:03 PM ║       3 ║
║              1 ║ 2/16/2012 11:11:04 PM ║ 2/16/2012 11:11:03 PM ║       3 ║
║              1 ║ 2/16/2012 11:11:05 PM ║ 2/16/2012 11:11:04 PM ║       3 ║
║              1 ║ 2/16/2012 11:22:06 PM ║ 2/16/2012 11:11:05 PM ║       4 ║
║              1 ║ 2/17/2012 11:05:03 PM ║ 2/16/2012 11:22:06 PM ║       5 ║
║              1 ║ 2/17/2012 11:09:03 PM ║ 2/17/2012 11:05:03 PM ║       5 ║
║              1 ║ 2/17/2012 11:11:03 PM ║ 2/17/2012 11:09:03 PM ║       5 ║
║              2 ║ 2/15/2012 11:53:18 AM ║ 1/1/0001 12:00:00 AM  ║       6 ║
║              2 ║ 2/16/2012 11:54:01 AM ║ 2/15/2012 11:53:18 AM ║       7 ║
║              2 ║ 2/16/2012 11:54:02 AM ║ 2/16/2012 11:54:01 AM ║       7 ║
║              3 ║ 2/16/2012 11:53:50 AM ║ 1/1/0001 12:00:00 AM  ║       8 ║
║              3 ║ 2/16/2012 11:54:50 AM ║ 2/16/2012 11:53:50 AM ║       8 ║
║              4 ║ 2/16/2012 11:54:04 AM ║ 1/1/0001 12:00:00 AM  ║       9 ║
╚════════════════╩═══════════════════════╩═══════════════════════╩═════════╝

Body:
Setting up some dummy data to mirror your stated question:

create table some_data
(
    id int,
    MessageDate1 datetime,
    MessageDate2 datetime
)

insert into some_data values
(1,'2012-02-15 11:53:16', '2012-02-15 00:00:00'),
(2,'2012-02-16 11:53:20', '2012-02-15 11:53:16'),
(3,'2012-02-16 11:54:01', '2012-02-15 11:53:20'),
(4,'2012-02-16 23:05:03', '2012-02-16 11:54:01'),
(5,'2012-02-16 23:09:03', '2012-02-16 23:05:03'),
(6,'2012-02-16 23:11:03', '2012-02-16 23:09:03'),
(7,'2012-02-16 23:11:04', '2012-02-16 23:11:03'),
(8,'2012-02-16 23:11:05', '2012-02-16 23:11:04'),
(9,'2012-02-16 23:22:06', '2012-02-16 23:11:05'),
(10,'2012-02-17 23:05:03', '2012-02-16 23:22:06'),
(11,'2012-02-17 23:09:03', '2012-02-17 23:05:03'),
(12,'2012-02-17 23:11:03', '2012-02-17 23:09:03'),
(13,'2012-02-15 11:53:18', '2012-02-15 00:00:00'),
(14,'2012-02-16 11:54:01', '2012-02-15 11:53:18'),
(15,'2012-02-16 11:54:02', '2012-02-16 11:54:01'),
(16,'2012-02-16 11:53:50', '2012-02-16 12:00:00'),
(17,'2012-02-16 11:54:50', '2012-02-16 11:53:50'),
(18,'2012-02-16 11:54:04', '2012-02-16 00:00:00')

I've included an id field to allow me to order the records as I could not see any particular logic to how your sample data was ordered and the way the count works is dependent on the order of the records. I also replaced date values you had for the year 0001.

This query gives what I believe the desired output is, where the Count is incremented each time a record is encountered where the difference between the MessageDate1 and MessageDate2 fields is more than 10 minutes:

select
    MessageDate1,
    MessageDate2,
    sum(GT_10M) over (order by id) as [Count]
from
(
    select
        id,
        MessageDate1,
        MessageDate2,
        case when abs(datediff(minute,MessageDate2,MessageDate1)) > 10 then 1 else 0 end as GT_10M
    from some_data
) r

Results:

/-----------------------------------------------------------\
|      MessageDate1       |      MessageDate2       | Count |
|-------------------------|-------------------------|-------|
| 2012-02-15 11:53:16.000 | 2012-02-15 00:00:00.000 |   1   |
| 2012-02-16 11:53:20.000 | 2012-02-15 11:53:16.000 |   2   |
| 2012-02-16 11:54:01.000 | 2012-02-15 11:53:20.000 |   3   |
| 2012-02-16 23:05:03.000 | 2012-02-16 11:54:01.000 |   4   |
| 2012-02-16 23:09:03.000 | 2012-02-16 23:05:03.000 |   4   |
| 2012-02-16 23:11:03.000 | 2012-02-16 23:09:03.000 |   4   |
| 2012-02-16 23:11:04.000 | 2012-02-16 23:11:03.000 |   4   |
| 2012-02-16 23:11:05.000 | 2012-02-16 23:11:04.000 |   4   |
| 2012-02-16 23:22:06.000 | 2012-02-16 23:11:05.000 |   5   |
| 2012-02-17 23:05:03.000 | 2012-02-16 23:22:06.000 |   6   |
| 2012-02-17 23:09:03.000 | 2012-02-17 23:05:03.000 |   6   |
| 2012-02-17 23:11:03.000 | 2012-02-17 23:09:03.000 |   6   |
| 2012-02-15 11:53:18.000 | 2012-02-15 00:00:00.000 |   7   |
| 2012-02-16 11:54:01.000 | 2012-02-15 11:53:18.000 |   8   |
| 2012-02-16 11:54:02.000 | 2012-02-16 11:54:01.000 |   8   |
| 2012-02-16 11:53:50.000 | 2012-02-16 12:00:00.000 |   8   |
| 2012-02-16 11:54:50.000 | 2012-02-16 11:53:50.000 |   8   |
| 2012-02-16 11:54:04.000 | 2012-02-16 00:00:00.000 |   9   |
\-----------------------------------------------------------/


问:
Shiny R assign variable based on dropdown using data.frame column and pass this variable to plotly to plot visualization
i have a data.frame from my DB, and i am trying to create a R Shiny Web App in which i could choose from the two dropdown menus (based on values from combination of row and column in my data.frame) and pass those variables to plotly

Lets say i have this data in my data frame:

```<code># |User|N00   |Percentage|N01 |
  |----|------|----------|----|
  |35  |2229  | 4.46830  |918 |
  |37  |153   | 0.00307  |0   |
  |39  |1557  | 0.03120  |0   |
  |41  |4997  | 0.10014  |0   |
  |42  |1     | 0.00002  |0   |
  |44  |12221 | 0.24490  |0   |
  |46  |5     | 0.00010  |0   |
  |50  |342   | 0.00685  |0   |
  |51  |123   | 0.00246  |0   |
  |56  |2     | 0.00004  |1   |
  |57  |0     | 0.00000  |0   |
  |60  |62275 |1.24796   |2799|

</code>```

What i would like to do is to have one dropdown with values in Column "User" and second dropdown with Headers, so i could choose "User" and "Header" and get back the appropriate result (data.frame).

So what i would need from the combination of the two dropdowns is to do something like this:

```<code>select(data_to_choose_from, User, values)[data_to_choose_from$id==values2, ]
</code>```

Where values is the result of first dropdown (user), and values2 is the result of the second dropdown (headers), which looks like this:

So when i choose for example User "35" and Columnn "N00", i would like to get this result:

```<code> |User|N00   |
 |----|------|
 |35  |2229  |
</code>```

After i get this result i would like to pass the number in Column "N00" to some variable and create gauge with this number that would for example look like this (this is just and example, i have to tweak this to make it more "legible"):

I have this:

```<code>library(shiny) #Load libraries
library(plotly) #Load libraries

data_to_choose_from <- data.frame(a) #Assign data from data.frame(a), which is data i have from my DB to new variable

ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(
            selectizeInput("User", "User", choices=NULL, selected=NULL), #First dropdown
            selectizeInput("Metrics", "Metrics", choices=NULL, selected=NULL), #Second dropdown
            textOutput("values"), #Show what did i choose in the first dropdown
            textOutput("values2"), #Show what did i choose in the second dropdown
            tableOutput("table") #Output tha table based on my choices in dropdowns
        ),
        mainPanel(
            plotlyOutput('p') #Plot a visualization base on data from output table
        )
    )
)

server <- function(input, output, session) { #First dropdown, reference to my data.frame
    updateSelectizeInput(session, 'User',
                         choices = data_to_choose_from$User,
                         server = TRUE
    )
    updateSelectizeInput(session, 'Metrics',
                         choices = names(data_to_choose_from), #Second dropdown, reference to my data.frame
                         server = TRUE
    )

    output$values <- renderText({(input$User)}) #Output of first dropdown

    output$values2 <- renderText({(input$Metrics)}) #Output of second dropdown

    output$values3 <- as.vector(select(data_to_choose_from, values)[data_to_choose_from$id==values2, ]) #Put this as vector to plot_ly

    output$table <- select(data_to_choose_from, id, values)[data_to_choose_from$id==values2, ] #Filtered data.frame output based on original data

    output$plot <- renderPlotly( #Here i would like to create the plot to render in mainpanel
    p <- plot_ly(
        type = "indicator",
        mode = "gauge+number+delta",
        value = i,
        title = list(text = values2, font = list(size = 24)),
        delta = list(reference = 400, increasing = list(color = "RebeccaPurple")),
        gauge = list(
            axis = list(range = list(NULL, 500), tickwidth = 1, tickcolor = "darkblue"),
            bar = list(color = "darkblue"),
            bgcolor = "white",
            borderwidth = 2,
            bordercolor = "gray",
            steps = list(
                list(range = c(0, values3), color = "cyan"),
                list(range = c(values3, 400), color = "royalblue")),
            threshold = list(
               line = list(color = "red", width = 4),
                thickness = 0.75,
                value = values3 + 100))) %>%
        layout(
            margin = list(l=20,r=30),
            paper_bgcolor = "lavender",
            font = list(color = "darkblue", family = "Arial")))
}
shinyApp(ui, server)
</code>```

Unfortunately this does not work, i suppose my code is wrong from the ground up, i try to follow the documentation but i am kinda lost..

I am trying to learn R and i am confused as to how variables and Shiny R in general works, any information that would help me to achieve what i want would be greatly appreacited, if there is something unclear please let me know and i will edit my question, thanks

答:
There are multiple problems.

When you do output$values <- renderSomething({......}), you can't access to ...... by calling values (you even can't call output$values).

Replace output$values3 with

```<code>  values3 <- reactive({
    req(input$User, input$Metrics)
    data_to_choose_from[data_to_choose_from$User == input$User, input$Metrics]
  })
</code>```

Now you can get the value of values3 by calling values3(). So replace values3 in your renderPlotly with values3(). And replace text = values2 with text = input$Metrics.

The line req(input$User, input$Metrics) means that input$User and input$Metrics must be available. This avoids an error at the launching of the app because these variables are available only after the action of updateSelectizeInput.

If you want to render a table, use renderTable:

```<code>  output$table <- renderTable({
    req(input$User, input$Metrics)
    subset(data_to_choose_from, User == input$User, select = c("User", input$Metrics))
  })
</code>```

You do output$plot <- renderPlotly({ p <- plot_ly(.......) }) so in your ui that should be plotlyOutput("plot"), not plotlyOutput("p"). The p <- is useless, you can remove it.

Now in plot_ly you do value = i but i is not defined. I don't know what you intended to do (I'm not familiar with this kind of plots).

Body:
i have a data.frame from my DB, and i am trying to create a R Shiny Web App in which i could choose from the two dropdown menus (based on values from combination of row and column in my data.frame) and pass those variables to plotly

Lets say i have this data in my data frame:

# |User|N00   |Percentage|N01 |
  |----|------|----------|----|
  |35  |2229  | 4.46830  |918 |
  |37  |153   | 0.00307  |0   |
  |39  |1557  | 0.03120  |0   |
  |41  |4997  | 0.10014  |0   |
  |42  |1     | 0.00002  |0   |
  |44  |12221 | 0.24490  |0   |
  |46  |5     | 0.00010  |0   |
  |50  |342   | 0.00685  |0   |
  |51  |123   | 0.00246  |0   |
  |56  |2     | 0.00004  |1   |
  |57  |0     | 0.00000  |0   |
  |60  |62275 |1.24796   |2799|

What i would like to do is to have one dropdown with values in Column "User" and second dropdown with Headers, so i could choose "User" and "Header" and get back the appropriate result (data.frame).

So what i would need from the combination of the two dropdowns is to do something like this:

select(data_to_choose_from, User, values)[data_to_choose_from$id==values2, ]

Where values is the result of first dropdown (user), and values2 is the result of the second dropdown (headers), which looks like this:

So when i choose for example User "35" and Columnn "N00", i would like to get this result:

 |User|N00   |
 |----|------|
 |35  |2229  |

After i get this result i would like to pass the number in Column "N00" to some variable and create gauge with this number that would for example look like this (this is just and example, i have to tweak this to make it more "legible"):

I have this:

library(shiny) #Load libraries
library(plotly) #Load libraries

data_to_choose_from <- data.frame(a) #Assign data from data.frame(a), which is data i have from my DB to new variable

ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(
            selectizeInput("User", "User", choices=NULL, selected=NULL), #First dropdown
            selectizeInput("Metrics", "Metrics", choices=NULL, selected=NULL), #Second dropdown
            textOutput("values"), #Show what did i choose in the first dropdown
            textOutput("values2"), #Show what did i choose in the second dropdown
            tableOutput("table") #Output tha table based on my choices in dropdowns
        ),
        mainPanel(
            plotlyOutput('p') #Plot a visualization base on data from output table
        )
    )
)

server <- function(input, output, session) { #First dropdown, reference to my data.frame
    updateSelectizeInput(session, 'User',
                         choices = data_to_choose_from$User,
                         server = TRUE
    )
    updateSelectizeInput(session, 'Metrics',
                         choices = names(data_to_choose_from), #Second dropdown, reference to my data.frame
                         server = TRUE
    )

    output$values <- renderText({(input$User)}) #Output of first dropdown

    output$values2 <- renderText({(input$Metrics)}) #Output of second dropdown

    output$values3 <- as.vector(select(data_to_choose_from, values)[data_to_choose_from$id==values2, ]) #Put this as vector to plot_ly

    output$table <- select(data_to_choose_from, id, values)[data_to_choose_from$id==values2, ] #Filtered data.frame output based on original data

    output$plot <- renderPlotly( #Here i would like to create the plot to render in mainpanel
    p <- plot_ly(
        type = "indicator",
        mode = "gauge+number+delta",
        value = i,
        title = list(text = values2, font = list(size = 24)),
        delta = list(reference = 400, increasing = list(color = "RebeccaPurple")),
        gauge = list(
            axis = list(range = list(NULL, 500), tickwidth = 1, tickcolor = "darkblue"),
            bar = list(color = "darkblue"),
            bgcolor = "white",
            borderwidth = 2,
            bordercolor = "gray",
            steps = list(
                list(range = c(0, values3), color = "cyan"),
                list(range = c(values3, 400), color = "royalblue")),
            threshold = list(
               line = list(color = "red", width = 4),
                thickness = 0.75,
                value = values3 + 100))) %>%
        layout(
            margin = list(l=20,r=30),
            paper_bgcolor = "lavender",
            font = list(color = "darkblue", family = "Arial")))
}
shinyApp(ui, server)

Unfortunately this does not work, i suppose my code is wrong from the ground up, i try to follow the documentation but i am kinda lost..

I am trying to learn R and i am confused as to how variables and Shiny R in general works, any information that would help me to achieve what i want would be greatly appreacited, if there is something unclear please let me know and i will edit my question, thanks

Body:
There are multiple problems.

When you do output$values <- renderSomething({......}), you can't access to ...... by calling values (you even can't call output$values).

Replace output$values3 with

  values3 <- reactive({
    req(input$User, input$Metrics)
    data_to_choose_from[data_to_choose_from$User == input$User, input$Metrics]
  })

Now you can get the value of values3 by calling values3(). So replace values3 in your renderPlotly with values3(). And replace text = values2 with text = input$Metrics.

The line req(input$User, input$Metrics) means that input$User and input$Metrics must be available. This avoids an error at the launching of the app because these variables are available only after the action of updateSelectizeInput.

If you want to render a table, use renderTable:

  output$table <- renderTable({
    req(input$User, input$Metrics)
    subset(data_to_choose_from, User == input$User, select = c("User", input$Metrics))
  })

You do output$plot <- renderPlotly({ p <- plot_ly(.......) }) so in your ui that should be plotlyOutput("plot"), not plotlyOutput("p"). The p <- is useless, you can remove it.

Now in plot_ly you do value = i but i is not defined. I don't know what you intended to do (I'm not familiar with this kind of plots).


问:
SQL get all raw base GROUP BY
I have table with 3 columns: id, frame and size.

I want to write query that get the id of the max size per frame.

I tried:

```<code>SELECT frame, MAX(size) FROM table1 GROUP BY frame
</code>```

I get:

```<code>    frame    |    size
      0      |     9.5
      1      |    10.6
</code>```

but how can I get the id also with the result?

答:
A method that works well in most databases is:

```<code>select t1.*
from table1 t1
where t1.size = (select max(tt2.size) from table1 tt1 where tt1.frame = t1.frame);
</code>```

In particular, this can take advantage of an index on table1(frame, size).

Another common method is use to row_number() or rank():

```<code>select t1.*
from (select t1.*,
             row_number() over (partition by frame order by size desc) as seqnum
      from table1 t1
     ) t1
where seqnum = 1;
</code>```

Title: SQL get all raw base GROUP BY

Body:
I have table with 3 columns: id, frame and size.

I want to write query that get the id of the max size per frame.

I tried:

SELECT frame, MAX(size) FROM table1 GROUP BY frame

I get:

    frame    |    size
      0      |     9.5
      1      |    10.6

but how can I get the id also with the result?

Body:
A method that works well in most databases is:

select t1.*
from table1 t1
where t1.size = (select max(tt2.size) from table1 tt1 where tt1.frame = t1.frame);

In particular, this can take advantage of an index on table1(frame, size).

Another common method is use to row_number() or rank():

select t1.*
from (select t1.*,
             row_number() over (partition by frame order by size desc) as seqnum
      from table1 t1
     ) t1
where seqnum = 1;


问:
C# write graph to coordinate-system
There are millions of data in my SQL DB and every Row is a Item with a Starttime and a duration. Now I want to visualize this Data to know which Data overlap at a time.

My idea is to create a coordinate-system with x-axis show the time and y-axis count the Item. Every graph is a line parallel to the x-axis start at Starttime + duration. The next graph is y+1 and also Starttime + Duration. Then I can see which Items overlap at which time.

How can I program that with C# any suggestion to solve this problem?

答:
I think you should take a look in the various chart controls out there:

Microsoft

Dundas

Nevron

whatever you find on the net

All of these support some kind of bar chart which could visualize this kind of data. But be aware that displaying can take a lot of time if you try to put millions of data points at a chart at once.

If high performance and mass of data is your constraint you should maybe take a look at one of these:

Lightning Chart

Measurement Studio

Dynamic Data Display

whatever you find on the net

Title: C# write graph to coordinate-system

LastEditorDisplayName: Aryabhatta


问:
Angular Error: No provider for ObservableMedia
I am trying to user ObservableMedia. Application compiles successfully but in browser console i see this error

ERROR Error: No provider for ObservableMedia!
      at injectionError (core.es5.js:1169)
      at noProviderError (core.es5.js:1207)

Here is my my code

```<code>import { Component , OnInit, ViewChild} from '@angular/core';
    import {Observable} from 'rxjs/Rx';
    import {MediaChange, ObservableMedia} from "@angular/flex-layout";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],

})
export class AppComponent implements OnInit {

constructor(
  public media: ObservableMedia) {

 }

  routeLinkClick() {
    if (!this.media.isActive('gt-xs')) {
      this.sidenav.toggle();
    }
  }
</code>```

Please help. thanks

答:
ObservableMedia replaced by MediaObserver from @angular/flex-layout v7.0.0-beta.24 (2019-03-17)

Before:

import {MediaChange, ObservableMedia} from "@angular/flex-layout";
  constructor(public media: ObservableMedia) {}

After:

```<code>import {MediaChange, MediaObserver} from "@angular/flex-layout";
constructor(public media: MediaObserver) {}
</code>```

Body:
I am trying to user ObservableMedia. Application compiles successfully but in browser console i see this error

ERROR Error: No provider for ObservableMedia!
      at injectionError (core.es5.js:1169)
      at noProviderError (core.es5.js:1207)

Here is my my code

import { Component , OnInit, ViewChild} from '@angular/core';
    import {Observable} from 'rxjs/Rx';
    import {MediaChange, ObservableMedia} from "@angular/flex-layout";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],

})
export class AppComponent implements OnInit {

constructor(
  public media: ObservableMedia) {

 }

  routeLinkClick() {
    if (!this.media.isActive('gt-xs')) {
      this.sidenav.toggle();
    }
  }

Please help. thanks

Body:
ObservableMedia replaced by MediaObserver from @angular/flex-layout v7.0.0-beta.24 (2019-03-17)

Before:

import {MediaChange, ObservableMedia} from "@angular/flex-layout";
  constructor(public media: ObservableMedia) {}

After:

import {MediaChange, MediaObserver} from "@angular/flex-layout";
constructor(public media: MediaObserver) {}


问:
How to set a zoom in when I select the marker in the map?
How do I set the zoom only for the marker selected on the map and not for the focused location?
here is my code:
I tried lot of codes but I have no success yet.

```<code>export default class Mapper extends Component {
  constructor(props) {
    super(props);
    this.state = {
      focusedLocation: {
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta:
          (Dimensions.get('window').width / Dimensions.get('window').height) *
         0.00522,
      },
      locations: locations,
    };
    this.switchMapType = this.switchMapType.bind(this);
  }

  onPressZoomIn() {
    this.region = {
      latitude: this.state.focusedLocation.latitude,
      longitude: this.state.focusedLocation.longitude,
      latitudeDelta: this.state.focusedLocation.latitudeDelta * 0.5,
      longitudeDelta: this.state.focusedLocation.longitudeDelta * 0.5,
    };

    this.setState({
      focusedLocation: {
        latitudeDelta: this.region.latitudeDelta,
        longitudeDelta: this.region.longitudeDelta,
        latitude: this.region.latitude,
        longitude: this.region.longitude,
      },
    });
    this.map.animateToRegion(this.region, 500);
  }

  onPressZoomOut() {
    this.region = {
      latitude: this.state.focusedLocation.latitude,
      longitude: this.state.focusedLocation.longitude,
      latitudeDelta: this.state.focusedLocation.latitudeDelta / 0.5,
      longitudeDelta: this.state.focusedLocation.longitudeDelta / 0.5,
    };
    this.setState({
      focusedLocation: {
        latitudeDelta: this.region.latitudeDelta,
        longitudeDelta: this.region.longitudeDelta,
        latitude: this.region.latitude,
        longitude: this.region.longitude,
      },
    });
    this.map.animateToRegion(this.region, 500);
  }
  render() {
    return (
      <View style={styles.container}>
       <StatusBar hidden />
        <MapView
          //initialRegion={initialRegion}
          style={styles.mapView}
          rotateEnabled={true}
          scrollEnabled={true}
          showsMyLocationButton={false}
          showsUserLocation={true}
          zoomEnabled={true}
          mapType={this.state.mapType}
          showsPointsOfInterest={false}
          showBuildings={false}
          onMapReady={this._mapReady}
          ref={ref => (this.map = ref)}>
          {locations.map(
            (locations, id, latitude, longitude, hora, linha, prestadora) => (
              console.log(locations.latitude, locations.latitude),
              (
                <MapView.Marker
                  onPress={this.pickLocationHandler}
                  ref={mark => (locations.mark = mark)}
                  key={id}
                  title={locations.linha + ' - ' + locations.prestadora}
                  pinColor={'tomato'}
                  description={
                    'Aguarde o seu transporte a partir de: ' + locations.hora
                  }
                  coordinate={{
                    latitude: JSON.parse(locations.latitude),
                    longitude: JSON.parse(locations.longitude),
                  }}
                />
              )
            )
          )}
        </MapView>
        ...
        <ScrollView
          style={styles.placesContainer}
          horizontal
          pagingEnabled
          showsHorizontalScrollIndicator={false}
          onMomentumScrollEnd={e => {
            const locations =
              e.nativeEvent.contentOffset.x > 0
                ? e.nativeEvent.contentOffset.x / Dimensions.get('window').width
                : 0;

            const { latitude, longitude, mark } = this.state.locations[
              locations
            ];

            this.map.animateToCoordinate(
              {
                latitude: JSON.parse(latitude),
                longitude: JSON.parse(longitude),
              },
              500
            );

            setTimeout(() => {
              mark.showCallout();
            }, 500);
          }}>
          {locations.map(locations => (
            <View key={locations.id} style={styles.place}>
              <Text style={styles.title}>Ponto {locations.id} </Text>
              <Text style={styles.text}>A partir de: {locations.hora}</Text>
              <Image
                source={require('./assets/expo.symbol.white.png')}
                style={{
                  marginLeft: Dimensions.get('window').width / 1.5,
                  width: 67,
                  height: 67,
                  tintColor: '#FF3D00',
                }}
              />
            </View>
          ))}
        </ScrollView>
      </View>
    );
  }
}
</code>```

How can I fix it? for when I press the button zoom in, for example, it takes a zoom in the specific marker selected?

Here is the full code for your view: https://snack.expo.io/@matheus_cbrl/zoomin-zoomout

here is the code to pick Location by Handler marker:

```<code>pickLocationHandler = event => {
    const coords = event.nativeEvent.coordinate;
    console.log('Location picker Marker', coords);
    this.map.animateToRegion({
      ...this.state.focusedlocation,
      latitude: coords.latitude,
      longitude: coords.longitude,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta:
          (Dimensions.get('window').width / Dimensions.get('window').height) *
          0.00522,
    });

    this.setState(prevState => {
      return {
        focusedlocation: {
          ...prevState.focusedlocation,
          latitude: coords.latitude,
          longitude: coords.longitude,
        },
        locationChosen: true,
      };
    });
  };
</code>```

答:
I found a solution:

First:

```<code>  _mapReady = () => {
    this.state.locations[0].mark.showCallout();
    this.animate(); <---ADD THIS METHOD
  };
</code>```

Second
Create this function, animating to the first point of your interest...

```<code>  animate(){
    let r = {
        latitude: JSON.parse(this.state.locations[0].latitude),
        longitude: JSON.parse(this.state.locations[0].longitude),
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta:
        (Dimensions.get('window').width / Dimensions.get('window').height) *
        0.00522,
    };
    this.map.animateToRegion(r, 500);
}
</code>```

this code will produce a zoom in the first marker of your interest.. check out!!

Body:
How do I set the zoom only for the marker selected on the map and not for the focused location?
here is my code:
I tried lot of codes but I have no success yet.

export default class Mapper extends Component {
  constructor(props) {
    super(props);
    this.state = {
      focusedLocation: {
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta:
          (Dimensions.get('window').width / Dimensions.get('window').height) *
         0.00522,
      },
      locations: locations,
    };
    this.switchMapType = this.switchMapType.bind(this);
  }

  onPressZoomIn() {
    this.region = {
      latitude: this.state.focusedLocation.latitude,
      longitude: this.state.focusedLocation.longitude,
      latitudeDelta: this.state.focusedLocation.latitudeDelta * 0.5,
      longitudeDelta: this.state.focusedLocation.longitudeDelta * 0.5,
    };

    this.setState({
      focusedLocation: {
        latitudeDelta: this.region.latitudeDelta,
        longitudeDelta: this.region.longitudeDelta,
        latitude: this.region.latitude,
        longitude: this.region.longitude,
      },
    });
    this.map.animateToRegion(this.region, 500);
  }

  onPressZoomOut() {
    this.region = {
      latitude: this.state.focusedLocation.latitude,
      longitude: this.state.focusedLocation.longitude,
      latitudeDelta: this.state.focusedLocation.latitudeDelta / 0.5,
      longitudeDelta: this.state.focusedLocation.longitudeDelta / 0.5,
    };
    this.setState({
      focusedLocation: {
        latitudeDelta: this.region.latitudeDelta,
        longitudeDelta: this.region.longitudeDelta,
        latitude: this.region.latitude,
        longitude: this.region.longitude,
      },
    });
    this.map.animateToRegion(this.region, 500);
  }
  render() {
    return (
      <View style={styles.container}>
       <StatusBar hidden />
        <MapView
          //initialRegion={initialRegion}
          style={styles.mapView}
          rotateEnabled={true}
          scrollEnabled={true}
          showsMyLocationButton={false}
          showsUserLocation={true}
          zoomEnabled={true}
          mapType={this.state.mapType}
          showsPointsOfInterest={false}
          showBuildings={false}
          onMapReady={this._mapReady}
          ref={ref => (this.map = ref)}>
          {locations.map(
            (locations, id, latitude, longitude, hora, linha, prestadora) => (
              console.log(locations.latitude, locations.latitude),
              (
                <MapView.Marker
                  onPress={this.pickLocationHandler}
                  ref={mark => (locations.mark = mark)}
                  key={id}
                  title={locations.linha + ' - ' + locations.prestadora}
                  pinColor={'tomato'}
                  description={
                    'Aguarde o seu transporte a partir de: ' + locations.hora
                  }
                  coordinate={{
                    latitude: JSON.parse(locations.latitude),
                    longitude: JSON.parse(locations.longitude),
                  }}
                />
              )
            )
          )}
        </MapView>
        ...
        <ScrollView
          style={styles.placesContainer}
          horizontal
          pagingEnabled
          showsHorizontalScrollIndicator={false}
          onMomentumScrollEnd={e => {
            const locations =
              e.nativeEvent.contentOffset.x > 0
                ? e.nativeEvent.contentOffset.x / Dimensions.get('window').width
                : 0;

            const { latitude, longitude, mark } = this.state.locations[
              locations
            ];

            this.map.animateToCoordinate(
              {
                latitude: JSON.parse(latitude),
                longitude: JSON.parse(longitude),
              },
              500
            );

            setTimeout(() => {
              mark.showCallout();
            }, 500);
          }}>
          {locations.map(locations => (
            <View key={locations.id} style={styles.place}>
              <Text style={styles.title}>Ponto {locations.id} </Text>
              <Text style={styles.text}>A partir de: {locations.hora}</Text>
              <Image
                source={require('./assets/expo.symbol.white.png')}
                style={{
                  marginLeft: Dimensions.get('window').width / 1.5,
                  width: 67,
                  height: 67,
                  tintColor: '#FF3D00',
                }}
              />
            </View>
          ))}
        </ScrollView>
      </View>
    );
  }
}

How can I fix it? for when I press the button zoom in, for example, it takes a zoom in the specific marker selected?

Here is the full code for your view: https://snack.expo.io/@matheus_cbrl/zoomin-zoomout

here is the code to pick Location by Handler marker:

pickLocationHandler = event => {
    const coords = event.nativeEvent.coordinate;
    console.log('Location picker Marker', coords);
    this.map.animateToRegion({
      ...this.state.focusedlocation,
      latitude: coords.latitude,
      longitude: coords.longitude,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta:
          (Dimensions.get('window').width / Dimensions.get('window').height) *
          0.00522,
    });

    this.setState(prevState => {
      return {
        focusedlocation: {
          ...prevState.focusedlocation,
          latitude: coords.latitude,
          longitude: coords.longitude,
        },
        locationChosen: true,
      };
    });
  };

Body:
I found a solution:

First:

  _mapReady = () => {
    this.state.locations[0].mark.showCallout();
    this.animate(); <---ADD THIS METHOD
  };

Second
Create this function, animating to the first point of your interest...

  animate(){
    let r = {
        latitude: JSON.parse(this.state.locations[0].latitude),
        longitude: JSON.parse(this.state.locations[0].longitude),
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta:
        (Dimensions.get('window').width / Dimensions.get('window').height) *
        0.00522,
    };
    this.map.animateToRegion(r, 500);
}

this code will produce a zoom in the first marker of your interest.. check out!!


问:
How to remove eventlistener while passing the data to the listener using bind?
I am adding an event listener and then trying to remove it as shown:

Scenario-1

```<code>class A{
function A(){
   elem.addEventListener('mouseover',this.onMouseOver);
   elem.addEventListener('mouseout',this.onMouseOut);
}

function B(){
   elem.removeEventListener('mouseout', this.onMouseOut);
}

function onMouseOver(){

}
function onMouseOut(){
  console.log('-------------------------------mouse out-------------');
}
}
</code>```

In the above scenario my listener is getting removed but it is not getting removed when I bind some value as :

Scenario-2

```<code>class A{
function A(){
   elem.addEventListener('mouseover',this.onMouseOver);
   elem.addEventListener('mouseout',this.onMouseOut.bind(null,"A"));
}

function B(){
   elem.removeEventListener('mouseout', this.onMouseOut.bind(null,"A"));
}

function onMouseOver=()=>{

}
function onMouseOut=(name:string,e:any)=>{
  console.log('-------------------------------mouse out-------------'+name);
}
}
</code>```

Why event listener is getting removed in Scenario-1 and not in Scenario-2 ? How do I bind the value like Scenario-2 so that it will remove as well as add event listener ??

Thanks

答:
From the code and the usage of this, I assume this to be a object structure where this binds the functions together in a common context.

```<code>function A(){
   this.mouseOutFunctionImpl = this.onMouseOut.bind(null,"A");
   elem.addEventListener('mouseover',this.onMouseOver);
   elem.addEventListener('mouseout',this.mouseOutFunctionImpl);
}

function B(){
   elem.removeEventListener('mouseout', this.mouseOutFunctionImpl);
}

function onMouseOver=()=>{

}
function onMouseOut=(name:string,e:any)=>{
  console.log('-------------------------------mouse out-------------'+name);
}
</code>```

Body:
I am adding an event listener and then trying to remove it as shown:

Scenario-1

class A{
function A(){
   elem.addEventListener('mouseover',this.onMouseOver);
   elem.addEventListener('mouseout',this.onMouseOut);
}

function B(){
   elem.removeEventListener('mouseout', this.onMouseOut);
}

function onMouseOver(){

}
function onMouseOut(){
  console.log('-------------------------------mouse out-------------');
}
}

In the above scenario my listener is getting removed but it is not getting removed when I bind some value as :

Scenario-2

class A{
function A(){
   elem.addEventListener('mouseover',this.onMouseOver);
   elem.addEventListener('mouseout',this.onMouseOut.bind(null,"A"));
}

function B(){
   elem.removeEventListener('mouseout', this.onMouseOut.bind(null,"A"));
}

function onMouseOver=()=>{

}
function onMouseOut=(name:string,e:any)=>{
  console.log('-------------------------------mouse out-------------'+name);
}
}

Why event listener is getting removed in Scenario-1 and not in Scenario-2 ? How do I bind the value like Scenario-2 so that it will remove as well as add event listener ??

Thanks

Body:
From the code and the usage of this, I assume this to be a object structure where this binds the functions together in a common context.

function A(){
   this.mouseOutFunctionImpl = this.onMouseOut.bind(null,"A");
   elem.addEventListener('mouseover',this.onMouseOver);
   elem.addEventListener('mouseout',this.mouseOutFunctionImpl);
}

function B(){
   elem.removeEventListener('mouseout', this.mouseOutFunctionImpl);
}

function onMouseOver=()=>{

}
function onMouseOut=(name:string,e:any)=>{
  console.log('-------------------------------mouse out-------------'+name);
}


问:
Share local collection between Threads in C#
I have two methods as below

```<code>private void MethodB_GetId()
        {
            //Calling Method A constinuosly in different thread
            //Let's say its calling for Id = 1 to 100
        }

        private void MethodA_GetAll()
        {
            List<string> lst;
            lock(_locker)
            {
                lst = SomeService.Get(); //This get return all 100 ids in one shot.
                //Some other processing and then return result.
            }
        }
</code>```

Now client is calling MethodB_GetById continuously for fetching data for id: 1 to 100 randomly. (It require some of data from these 100 Ids, not all data)

MethodA_GetAll get all data from network may be cache or database in one shot. and return whole collection to method B, then method B extract record in which it is interested.

Now if MethodA_GetAll() makes GetALL() times multiple times and fetching same records will be useless. so i can put a lock around it one thread is fetching record then other will be blocked.

Let's When MethodA_GetAll called by Id = 1 acquire lock and all others are waiting for lock to be released.

What i want is one data is available by any one thread just don't make call again.

Solution option:
1. Make List global to that class and thread safe. (I don't have that option)

I require some how thread 1 tell all other threads that i have record don't go fetching record again.

something like

```<code>lock(_locker && Lst!=null) //Not here lst is local to every thread
{
   //If this satisfy then only fetch records
}
</code>```

Please excuse me for poorly framing question. I have posted this in little hurry.

答:
You can try double-check-locking lst:

```<code>private List<string> lst;

private void MethodA_GetAll()
{
    if (lst == null)
    {
        lock (_locker)
        {
            if (lst == null)
            {
                // do your thing
            }
        }
    }
}
</code>```

Body:
I have two methods as below

private void MethodB_GetId()
        {
            //Calling Method A constinuosly in different thread
            //Let's say its calling for Id = 1 to 100
        }

        private void MethodA_GetAll()
        {
            List<string> lst;
            lock(_locker)
            {
                lst = SomeService.Get(); //This get return all 100 ids in one shot.
                //Some other processing and then return result.
            }
        }

Now client is calling MethodB_GetById continuously for fetching data for id: 1 to 100 randomly. (It require some of data from these 100 Ids, not all data)

MethodA_GetAll get all data from network may be cache or database in one shot. and return whole collection to method B, then method B extract record in which it is interested.

Now if MethodA_GetAll() makes GetALL() times multiple times and fetching same records will be useless. so i can put a lock around it one thread is fetching record then other will be blocked.

Let's When MethodA_GetAll called by Id = 1 acquire lock and all others are waiting for lock to be released.

What i want is one data is available by any one thread just don't make call again.

Solution option:
1. Make List global to that class and thread safe. (I don't have that option)

I require some how thread 1 tell all other threads that i have record don't go fetching record again.

something like

lock(_locker && Lst!=null) //Not here lst is local to every thread
{
   //If this satisfy then only fetch records
}

Please excuse me for poorly framing question. I have posted this in little hurry.

Body:
You can try double-check-locking lst:

private List<string> lst;

private void MethodA_GetAll()
{
    if (lst == null)
    {
        lock (_locker)
        {
            if (lst == null)
            {
                // do your thing
            }
        }
    }
}


问:
How to build an efficient named array?
I want to have a type that both has named members and also is iterable, so one should be able to refer to the members by index, by label or from a for-each loop. One way to realise this would be to use std::unordered_map<std::string,T> with some helper data for the indices. Clearly this would be horribly inefficient as for each member access you need to hash a std::string.

My current attempt looks like this:

```<code>// named-array.h
#pragma once

#include <array>
#include <cstddef>

#define NamedArray_KeyDecl(Name, ...) enum class Name : std::size_t { __VA_ARGS__, NUM }

namespace util {
  template <typename K, typename T>
  struct NamedArray {
    static constexpr std::size_t cast(K k) {
      return static_cast<std::size_t>(k);
    }

    std::array<T,cast(K::NUM)> array;
    NamedArray(std::array<T,cast(K::NUM)> a) : array(a) {
    }
    constexpr T& operator[](K k) {
      return array[cast(k)];
    }
    constexpr T const& operator[](K k) const {
      return array[cast(k)];
    }
  };
}
</code>```

Which can be used like so:

```<code>  struct Gadget {
    int i;
    Gadget(int i) : i(i) {}
    void operator()() const {
      std::cout << "Gadget(" << i << ")\n";
    }
  };

  NamedArray_KeyDecl(Test1, a,b,c,d);

  util::NamedArray<Test1,Gadget> gadgets {{0,1,2,3}};
  // for each works:
  for (auto const& gadget: gadgets.array) {
    gadget();
  }
  // named access works:
  gadgets[Test1::b]();
  // access by index works:
  gadgets.array[1]();
</code>```

Exposing the array member could be avoided by forwarding all interface functions of std::array.

However, an obvious drawback is that

gadgets[Test1::b] is not as pretty as something along the lines of gadgets.member().b and

there is an exposed #define in a c++ header file (which is extremely smelly)

Is there a way to have a named array with the same performance as an std::array?

答:
Just define the enums as you want them. And leaving them unscoped is fine, you want the names to leak into the declaration's scope, and are helped by the implicit conversion to std::size_t.

```<code>template <typename K, typename T>
using NamedArray = std::array<T, K::NUM>;
</code>```

Then

```<code>struct Gadget {
  int i;
  Gadget(int i) : i(i) {}
  void operator()() const {
    std::cout << "Gadget(" << i << ")\n";
  }
};

enum Test1 : std::size_t { a, b, c, d, NUM };

int main() {
    NamedArray<Test1,Gadget> gadgets { 0,1,2,3 };
    // for each works:
    for (auto const& gadget: gadgets) {
      gadget();
    }
    // named access works:
    gadgets[b]();
    // access by index works:
    gadgets[1]();
}
</code>```

Title: How to build an efficient named array?

Body:
I want to have a type that both has named members and also is iterable, so one should be able to refer to the members by index, by label or from a for-each loop. One way to realise this would be to use std::unordered_map<std::string,T> with some helper data for the indices. Clearly this would be horribly inefficient as for each member access you need to hash a std::string.

My current attempt looks like this:

// named-array.h
#pragma once

#include <array>
#include <cstddef>

#define NamedArray_KeyDecl(Name, ...) enum class Name : std::size_t { __VA_ARGS__, NUM }

namespace util {
  template <typename K, typename T>
  struct NamedArray {
    static constexpr std::size_t cast(K k) {
      return static_cast<std::size_t>(k);
    }

    std::array<T,cast(K::NUM)> array;
    NamedArray(std::array<T,cast(K::NUM)> a) : array(a) {
    }
    constexpr T& operator[](K k) {
      return array[cast(k)];
    }
    constexpr T const& operator[](K k) const {
      return array[cast(k)];
    }
  };
}

Which can be used like so:

  struct Gadget {
    int i;
    Gadget(int i) : i(i) {}
    void operator()() const {
      std::cout << "Gadget(" << i << ")\n";
    }
  };

  NamedArray_KeyDecl(Test1, a,b,c,d);

  util::NamedArray<Test1,Gadget> gadgets {{0,1,2,3}};
  // for each works:
  for (auto const& gadget: gadgets.array) {
    gadget();
  }
  // named access works:
  gadgets[Test1::b]();
  // access by index works:
  gadgets.array[1]();

Exposing the array member could be avoided by forwarding all interface functions of std::array.

However, an obvious drawback is that

gadgets[Test1::b] is not as pretty as something along the lines of gadgets.member().b and

there is an exposed #define in a c++ header file (which is extremely smelly)

Is there a way to have a named array with the same performance as an std::array?

Body:
Just define the enums as you want them. And leaving them unscoped is fine, you want the names to leak into the declaration's scope, and are helped by the implicit conversion to std::size_t.

template <typename K, typename T>
using NamedArray = std::array<T, K::NUM>;

Then

struct Gadget {
  int i;
  Gadget(int i) : i(i) {}
  void operator()() const {
    std::cout << "Gadget(" << i << ")\n";
  }
};

enum Test1 : std::size_t { a, b, c, d, NUM };

int main() {
    NamedArray<Test1,Gadget> gadgets { 0,1,2,3 };
    // for each works:
    for (auto const& gadget: gadgets) {
      gadget();
    }
    // named access works:
    gadgets[b]();
    // access by index works:
    gadgets[1]();
}


问:
How to use built-in `slice` to access 2-d blocks in 2-d array?
I have a 2-d numpy array, for which I would like to modify 2-d blocks (like a 3x3 sub-block on a 9x9 sudoku board). Instead of using fancy indexing, I would like to use the built-in slice. Is there a way to make this work? I am thinking that the stride argument (third arg of slice) can be used to do this somehow, but I can't quite figure it out. My attempt is below.

```<code>import numpy as np

# make sample array (dim-1)
x = np.linspace(1, 81, 81).astype(int)
i = slice(0, 3)

print(x[i])
# [1 2 3]

# make sample array (dim-2)
X = x.reshape((9, 9))
</code>```

Say I wanted to access the first 3 rows and first 3 columns of X. I can do it with fancy indexing as:

```<code>print(X[:3, :3])
# [[ 1  2  3]
#  [10 11 12]
#  [19 20 21]]
</code>```

Trying to use similar logic to the dim-1 case with slice:

```<code>j = np.array([slice(0,3), slice(0,3)]) # wrong way to acccess
print(X[j])
</code>```

Throws the following error:

```<code>IndexError: arrays used as indices must be of integer (or boolean) type
</code>```

答:
If you subscript with X[:3, :3], then behind the curtains you pass a tuple, so (slice(3), slice(3)).

So you can construct a j with:

```<code>j = <b>(</b>slice(3)<b>,</b> slice(3)<b>)</b></code>```

or you can obtain the a, b block with:

```<code>j = (slice(3*a, 3*a+3), slice(3*b, 3*b+3))
</code>```

so here a=0 and b=1 for example will yield the X[0:3, 3:6] part. So a block that contains the first three rows and second three columns.

or you can make a tuple with a variable number of items. For example for an n-dimensional array, you can make an n-tuple that each has a slice(3) object:

```<code>j = (slice(3),)<b> * n</b></code>```

Body:
I have a 2-d numpy array, for which I would like to modify 2-d blocks (like a 3x3 sub-block on a 9x9 sudoku board). Instead of using fancy indexing, I would like to use the built-in slice. Is there a way to make this work? I am thinking that the stride argument (third arg of slice) can be used to do this somehow, but I can't quite figure it out. My attempt is below.

import numpy as np

# make sample array (dim-1)
x = np.linspace(1, 81, 81).astype(int)
i = slice(0, 3)

print(x[i])
# [1 2 3]

# make sample array (dim-2)
X = x.reshape((9, 9))

Say I wanted to access the first 3 rows and first 3 columns of X. I can do it with fancy indexing as:

print(X[:3, :3])
# [[ 1  2  3]
#  [10 11 12]
#  [19 20 21]]

Trying to use similar logic to the dim-1 case with slice:

j = np.array([slice(0,3), slice(0,3)]) # wrong way to acccess
print(X[j])

Throws the following error:

IndexError: arrays used as indices must be of integer (or boolean) type

Body:
If you subscript with X[:3, :3], then behind the curtains you pass a tuple, so (slice(3), slice(3)).

So you can construct a j with:

j = (slice(3), slice(3))

or you can obtain the a, b block with:

j = (slice(3*a, 3*a+3), slice(3*b, 3*b+3))

so here a=0 and b=1 for example will yield the X[0:3, 3:6] part. So a block that contains the first three rows and second three columns.

or you can make a tuple with a variable number of items. For example for an n-dimensional array, you can make an n-tuple that each has a slice(3) object:

j = (slice(3),) * n


问:
Correct way to import functions from file in python3
I'm building a simple python3 CLI for some scripting. I have troubles importing my own functions located in files that are in the same modules.

My file structure is

```<code>pycli/
├── README.md
├── pycli
  ├── __init__.py
  ├── cli.py
  └── funcmodule.py
</code>```

funcmodule.py:

```<code>def my_function(word):
    print("Hello %s" % word)
</code>```

cli.py:

```<code>#!/usr/bin/env python3

from pycli.funcmodule import my_function

def main():
    my_function('hello world')

if __name__ == '__main__':
    main()
</code>```

When I run ./pycli/cli.py from the command line I get

```<code>(venv) ➜  ./pycli/cli.py
Traceback (most recent call last):
  File "./pycli/cli.py", line 3, in <module>
    from pycli.funcmodule import my_function
ModuleNotFoundError: No module named 'pycli'
</code>```

When I run the cli.py from PyCharm or in Visual Studio Code, it works correctly. What is the correct way to import the function with python3+ (I don't care about python2)?

答:
This is a mismatch between how you're running the program and how your imports are set up. Your imports are set up as if there's a package involved, but you're running the program like there's no package.

The way you're running your program, the contents of the inner pycli folder are all top-level modules, and there is no pycli package. To run your program as a package submodule, you need to do so from somewhere the pycli package is importable (which, as things are, would be inside the outer pycli folder, but could be anywhere if you installed your package), and you need to run

```<code>python -m pycli.cli
</code>```

Body:
I'm building a simple python3 CLI for some scripting. I have troubles importing my own functions located in files that are in the same modules.

My file structure is

pycli/
├── README.md
├── pycli
  ├── __init__.py
  ├── cli.py
  └── funcmodule.py

funcmodule.py:

def my_function(word):
    print("Hello %s" % word)

cli.py:

#!/usr/bin/env python3

from pycli.funcmodule import my_function

def main():
    my_function('hello world')

if __name__ == '__main__':
    main()

When I run ./pycli/cli.py from the command line I get

(venv) ➜  ./pycli/cli.py
Traceback (most recent call last):
  File "./pycli/cli.py", line 3, in <module>
    from pycli.funcmodule import my_function
ModuleNotFoundError: No module named 'pycli'

When I run the cli.py from PyCharm or in Visual Studio Code, it works correctly. What is the correct way to import the function with python3+ (I don't care about python2)?

Body:
This is a mismatch between how you're running the program and how your imports are set up. Your imports are set up as if there's a package involved, but you're running the program like there's no package.

The way you're running your program, the contents of the inner pycli folder are all top-level modules, and there is no pycli package. To run your program as a package submodule, you need to do so from somewhere the pycli package is importable (which, as things are, would be inside the outer pycli folder, but could be anywhere if you installed your package), and you need to run

python -m pycli.cli


问:
Need help resolving an Angular 9 TypeScript Error (TypeCasting)
I've updated Angular from 4 to 9 and now, after being able to getting it to work, still getting some errors which I am not able to resolve.

My code:

```<code>this.getTrades().then( ( trades ) => {
    console.log( trades );
    this.trades = new MatTableDataSource<Trade>( trades );
});

getTrades() {
    let promise = new Promise( ( resolve, reject ) => {
        this.dataService.getTrades().subscribe( ( trades ) => {
            resolve( trades );
        });
    });
    return promise;
}

export interface Trade {
    ID: number;
    UserID: number;
    DateTime: Date;
    Exchange: Exchange;
    BaseCoin: Coin;
    MarketCoin: MarketCoin;
    Price: number;
    Amount: number;
    Total: number;
    Last: number;
    Type: Type;
    Status: Status;
    Symbol: string;
}
</code>```

getTrades() datasource:

```<code>getTrades() {

    return this.http.get( 'http://localhost:8888/currencytracker-api/json/get-trades.php' ).pipe(
    map( res => res.json() ));

}
</code>```

getTrades() returns a json array with the following data:

```<code>ID: 1
UserID: 1
DateTime: "2017-12-25T00:00:00+0000"
Exchange: {ID: 1, Title: "BitTrex"}
BaseCoin: {ID: 718, Abbr: "BTC"}
MarketCoin: {ID: 743, Abbr: "XVG"}
Price: "0.000013470000"
Amount: "1019.014328640000"
Total: 0.0137261230067808
Last: "0.000005470000"
Type: {ID: 1, Title: "Limit Buy"}
Status: {ID: 2, Title: "Closed"}
Symbol: "Ƀ"
</code>```

This is the error I get:

ERROR in src/app/components/trades/trades.component.ts:100:68 - error TS2345: Argument of type 'unknown' is not assignable to parameter of type 'Trade[]'. Type '{}' is missing the following properties from type 'Trade[]': length, pop, push, concat, and 26 more.

this.trades = new MatTableDataSource( trades );

Any help understanding this error and resolving it would be very appreciated. Thank you.

Update

When I declared the trades variable I did it as:

```<code>Trade[]
</code>```

Instead I have now declared it as:

```<code>MatTableDataSource<Trade>
</code>```

答:
You need to be more explicit about the types:

Firstly, use the most convenient  overload of HttpClient.get that requires a generic parameter and interprets the body as JSON.

Constructs a GET request that interprets the body as a JSON object and returns
    the response body in a given type.

```<code>getTrades(): Observable<Trade[]> {
    return this.http.get<Trade[]>( 'http://localhost:8888/currencytracker-api/json/get-trades.php' );
}
</code>```

then, add explicit types to getTrades()

```<code>getTrades(): Promise<Trade[]> {
    const promise = new Promise<Trade[]>( ( resolve, reject ) => {
      this.dataSource.getTrades().subscribe( ( trades ) => {
        resolve( trades );
      });
    });
    return promise;
  }
</code>```

Even better, drop the conversion to promise, and subscribe directly to the Observable returned by the dataSource.

```<code>this.dataSource.getTrades().subscribe( ( trades ) => {
    console.log( trades );
    this.trades = new MatTableDataSource<Trade>( trades );
});
</code>```

Update

Check if you use HttpClient from @angular/common/http, and not from @angular/core.
The @angular/http package was deprecated with the arrival of @angular/common/http, and was removed with Angular 8.

https://www.npmjs.com/package/@angular/http

Package no longer supported. Use @angular/common instead, see https://angular.io/guide/deprecations#angularhttp

Update 2
Your problems with assignment show that it was always incorrect.
MatTableDataSource<Trade> is not Trade[]

I strongly believe the reason it worked in your old project is that you used
TypeScript 2.x. Thus getTrades() was inferred to Promise<any>
With Typescript 3.x getTrades() (without explicit typing) is inferred to Promise<unknown>

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#new-unknown-top-type

TypeScript 3.0 introduces a new top type unknown. unknown is the type-safe counterpart of any. Anything is assignable to unknown, but unknown isn’t assignable to anything but itself and any without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.

Body:
I've updated Angular from 4 to 9 and now, after being able to getting it to work, still getting some errors which I am not able to resolve.

My code:

this.getTrades().then( ( trades ) => {
    console.log( trades );
    this.trades = new MatTableDataSource<Trade>( trades );
});

getTrades() {
    let promise = new Promise( ( resolve, reject ) => {
        this.dataService.getTrades().subscribe( ( trades ) => {
            resolve( trades );
        });
    });
    return promise;
}

export interface Trade {
    ID: number;
    UserID: number;
    DateTime: Date;
    Exchange: Exchange;
    BaseCoin: Coin;
    MarketCoin: MarketCoin;
    Price: number;
    Amount: number;
    Total: number;
    Last: number;
    Type: Type;
    Status: Status;
    Symbol: string;
}

getTrades() datasource:

getTrades() {

    return this.http.get( 'http://localhost:8888/currencytracker-api/json/get-trades.php' ).pipe(
    map( res => res.json() ));

}

getTrades() returns a json array with the following data:

ID: 1
UserID: 1
DateTime: "2017-12-25T00:00:00+0000"
Exchange: {ID: 1, Title: "BitTrex"}
BaseCoin: {ID: 718, Abbr: "BTC"}
MarketCoin: {ID: 743, Abbr: "XVG"}
Price: "0.000013470000"
Amount: "1019.014328640000"
Total: 0.0137261230067808
Last: "0.000005470000"
Type: {ID: 1, Title: "Limit Buy"}
Status: {ID: 2, Title: "Closed"}
Symbol: "Ƀ"

This is the error I get:

ERROR in src/app/components/trades/trades.component.ts:100:68 - error TS2345: Argument of type 'unknown' is not assignable to parameter of type 'Trade[]'. Type '{}' is missing the following properties from type 'Trade[]': length, pop, push, concat, and 26 more.

this.trades = new MatTableDataSource( trades );

Any help understanding this error and resolving it would be very appreciated. Thank you.

Update

When I declared the trades variable I did it as:

Trade[]

Instead I have now declared it as:

MatTableDataSource<Trade>

Body:
You need to be more explicit about the types:

Firstly, use the most convenient  overload of HttpClient.get that requires a generic parameter and interprets the body as JSON.

Constructs a GET request that interprets the body as a JSON object and returns
    the response body in a given type.

getTrades(): Observable<Trade[]> {
    return this.http.get<Trade[]>( 'http://localhost:8888/currencytracker-api/json/get-trades.php' );
}

then, add explicit types to getTrades()

getTrades(): Promise<Trade[]> {
    const promise = new Promise<Trade[]>( ( resolve, reject ) => {
      this.dataSource.getTrades().subscribe( ( trades ) => {
        resolve( trades );
      });
    });
    return promise;
  }

Even better, drop the conversion to promise, and subscribe directly to the Observable returned by the dataSource.

this.dataSource.getTrades().subscribe( ( trades ) => {
    console.log( trades );
    this.trades = new MatTableDataSource<Trade>( trades );
});

Update

Check if you use HttpClient from @angular/common/http, and not from @angular/core.
The @angular/http package was deprecated with the arrival of @angular/common/http, and was removed with Angular 8.

https://www.npmjs.com/package/@angular/http

Package no longer supported. Use @angular/common instead, see https://angular.io/guide/deprecations#angularhttp

Update 2
Your problems with assignment show that it was always incorrect.
MatTableDataSource<Trade> is not Trade[]

I strongly believe the reason it worked in your old project is that you used
TypeScript 2.x. Thus getTrades() was inferred to Promise<any>
With Typescript 3.x getTrades() (without explicit typing) is inferred to Promise<unknown>

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#new-unknown-top-type

TypeScript 3.0 introduces a new top type unknown. unknown is the type-safe counterpart of any. Anything is assignable to unknown, but unknown isn’t assignable to anything but itself and any without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.